blob: aad8f6f6f55e0fca0ae48cf65f6a11c8d45b9e54 [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
Dimitry Ivanov3f660572016-09-09 10:00:39 -070034#include "linker_debug.h"
Ryan Prichard80e40f02019-10-31 19:54:46 -070035#include "linker_debuggerd.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070036#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070037#include "linker_gdb_support.h"
38#include "linker_globals.h"
39#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080040#include "linker_relocate.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080041#include "linker_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070042#include "linker_utils.h"
43
Ryan Prichard249757b2019-11-01 17:18:28 -070044#include "private/bionic_auxv.h"
45#include "private/bionic_call_ifunc_resolver.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070046#include "private/bionic_globals.h"
47#include "private/bionic_tls.h"
48#include "private/KernelArgumentBlock.h"
49
Ryan Prichard8f639a42018-10-01 23:10:05 -070050#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070051#include "android-base/strings.h"
52#include "android-base/stringprintf.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070053
Christopher Ferris7a3681e2017-04-24 17:48:32 -070054#include <async_safe/log.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080055#include <bionic/libc_init_common.h>
Ryan Prichard45d13492019-01-03 02:51:30 -080056#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070057
Dimitry Ivanov3f660572016-09-09 10:00:39 -070058#include <vector>
59
Ryan Prichard8f639a42018-10-01 23:10:05 -070060__LIBC_HIDDEN__ extern "C" void _start();
Dimitry Ivanov3f660572016-09-09 10:00:39 -070061
62static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
63
Ryan Prichard9729f352018-07-13 22:40:26 -070064static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
65 ElfW(Addr)* base, ElfW(Addr)* load_bias);
66
Vic Yang1bf62b22019-08-13 14:53:28 -070067static void set_bss_vma_name(soinfo* si);
68
Dimitry Ivanov3f660572016-09-09 10:00:39 -070069// These should be preserved static to avoid emitting
70// RELATIVE relocations for the part of the code running
71// before linker links itself.
72
73// TODO (dimtiry): remove somain, rename solist to solist_head
74static soinfo* solist;
75static soinfo* sonext;
76static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070077static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020078static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070079
80void solist_add_soinfo(soinfo* si) {
81 sonext->next = si;
82 sonext = si;
83}
84
85bool solist_remove_soinfo(soinfo* si) {
86 soinfo *prev = nullptr, *trav;
87 for (trav = solist; trav != nullptr; trav = trav->next) {
88 if (trav == si) {
89 break;
90 }
91 prev = trav;
92 }
93
94 if (trav == nullptr) {
95 // si was not in solist
96 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
97 return false;
98 }
99
100 // prev will never be null, because the first entry in solist is
101 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700102 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700103 prev->next = si->next;
104 if (si == sonext) {
105 sonext = prev;
106 }
107
108 return true;
109}
110
111soinfo* solist_get_head() {
112 return solist;
113}
114
115soinfo* solist_get_somain() {
116 return somain;
117}
118
dimitry8b142562018-05-09 15:22:38 +0200119soinfo* solist_get_vdso() {
120 return vdso;
121}
122
Elliott Hughes90f96b92019-05-09 15:56:39 -0700123bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700124int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700125
126static std::vector<std::string> g_ld_preload_names;
127
128static std::vector<soinfo*> g_ld_preloads;
129
130static void parse_path(const char* path, const char* delimiters,
131 std::vector<std::string>* resolved_paths) {
132 std::vector<std::string> paths;
133 split_path(path, delimiters, &paths);
134 resolve_paths(paths, resolved_paths);
135}
136
137static void parse_LD_LIBRARY_PATH(const char* path) {
138 std::vector<std::string> ld_libary_paths;
139 parse_path(path, ":", &ld_libary_paths);
140 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
141}
142
143static void parse_LD_PRELOAD(const char* path) {
144 g_ld_preload_names.clear();
145 if (path != nullptr) {
146 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
147 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700148 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 -0700149 [](const std::string& s) { return s.empty(); }),
150 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700151 }
152}
153
154// An empty list of soinfos
155static soinfo_list_t g_empty_list;
156
Ryan Prichard07440a82018-11-22 03:16:06 -0800157static void add_vdso() {
158 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700159 if (ehdr_vdso == nullptr) {
160 return;
161 }
162
163 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
164
165 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
166 si->phnum = ehdr_vdso->e_phnum;
167 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
168 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
169 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
170
171 si->prelink_image();
Ryan Prichard339ecef2020-01-02 16:36:06 -0800172 si->link_image(SymbolLookupList(si), si, nullptr, nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200173 // prevents accidental unloads...
174 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
175 si->set_linked();
176 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200177
178 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700179}
180
Ryan Prichard04896452018-08-20 17:44:42 -0700181// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700182// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
183// this function is called.
184static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700185 auto& map = info.link_map_head;
186 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700187 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700188 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700189}
190
191extern "C" int __system_properties_init(void);
192
Ryan Prichard8f639a42018-10-01 23:10:05 -0700193struct ExecutableInfo {
194 std::string path;
195 struct stat file_stat;
196 const ElfW(Phdr)* phdr;
197 size_t phdr_count;
198 ElfW(Addr) entry_point;
199};
200
Ryan Prichard07440a82018-11-22 03:16:06 -0800201static ExecutableInfo get_executable_info() {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700202 ExecutableInfo result = {};
203
Tom Cherry66bc4282018-11-08 13:40:52 -0800204 if (is_first_stage_init()) {
205 // /proc fs is not mounted when first stage init starts. Therefore we can't
206 // use /proc/self/exe for init.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700207 stat("/init", &result.file_stat);
Tom Cherry66bc4282018-11-08 13:40:52 -0800208
209 // /init may be a symlink, so try to read it as such.
210 char path[PATH_MAX];
211 ssize_t path_len = readlink("/init", path, sizeof(path));
212 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
213 result.path = "/init";
214 } else {
215 result.path = std::string(path, path_len);
216 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700217 } else {
218 // 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("/proc/self/exe", &result.file_stat)) != 0) {
222 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700223 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700224 char path[PATH_MAX];
225 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
226 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
227 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
228 }
229 result.path = std::string(path, path_len);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700230 }
231
Ryan Prichard07440a82018-11-22 03:16:06 -0800232 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
233 result.phdr_count = getauxval(AT_PHNUM);
234 result.entry_point = getauxval(AT_ENTRY);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700235 return result;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700236}
237
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800238#if defined(__LP64__)
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700239static char kFallbackLinkerPath[] = "/system/bin/linker64";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800240#else
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700241static char kFallbackLinkerPath[] = "/system/bin/linker";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800242#endif
243
Ryan Prichard8f639a42018-10-01 23:10:05 -0700244__printflike(1, 2)
245static void __linker_error(const char* fmt, ...) {
246 va_list ap;
dimitry04f7a792017-09-29 11:52:17 +0200247
Ryan Prichard8f639a42018-10-01 23:10:05 -0700248 va_start(ap, fmt);
249 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
250 va_end(ap);
251
252 va_start(ap, fmt);
253 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
254 va_end(ap);
255
dimitry04f7a792017-09-29 11:52:17 +0200256 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700257}
258
Ryan Prichard8f639a42018-10-01 23:10:05 -0700259static void __linker_cannot_link(const char* argv0) {
260 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s\n",
261 argv0,
262 linker_get_error_buffer());
263}
264
265// Load an executable. Normally the kernel has already loaded the executable when the linker
266// starts. The linker can be invoked directly on an executable, though, and then the linker must
267// load it. This function doesn't load dependencies or resolve relocations.
268static ExecutableInfo load_executable(const char* orig_path) {
269 ExecutableInfo result = {};
270
271 if (orig_path[0] != '/') {
272 __linker_error("error: expected absolute path: \"%s\"\n", orig_path);
273 }
274
275 off64_t file_offset;
276 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
277 if (fd.get() == -1) {
278 __linker_error("error: unable to open file \"%s\"\n", orig_path);
279 }
280
281 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
282 __linker_error("error: unable to stat \"%s\": %s\n", result.path.c_str(), strerror(errno));
283 }
284
285 ElfReader elf_reader;
286 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
287 __linker_error("error: %s\n", linker_get_error_buffer());
288 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400289 address_space_params address_space;
290 if (!elf_reader.Load(&address_space)) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700291 __linker_error("error: %s\n", linker_get_error_buffer());
292 }
293
294 result.phdr = elf_reader.loaded_phdr();
295 result.phdr_count = elf_reader.phdr_count();
296 result.entry_point = elf_reader.entry_point();
297 return result;
298}
299
Tamas Petz8d55d182020-02-24 14:15:25 +0100300static void platform_properties_init() {
301#if defined(__aarch64__)
302 const unsigned long hwcap2 = getauxval(AT_HWCAP2);
303 g_platform_properties.bti_supported = (hwcap2 & HWCAP2_BTI) != 0;
304#endif
305}
306
Ryan Prichard8f639a42018-10-01 23:10:05 -0700307static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800308 ProtectedDataGuard guard;
309
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700310#if TIMING
311 struct timeval t0, t1;
312 gettimeofday(&t0, 0);
313#endif
314
315 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800316 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700317
318 // Initialize system properties
319 __system_properties_init(); // may use 'environ'
320
Tamas Petz8d55d182020-02-24 14:15:25 +0100321 // Initialize platform properties.
322 platform_properties_init();
323
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700324 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700325 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700326
327 g_linker_logger.ResetState();
328
329 // Get a few environment variables.
330 const char* LD_DEBUG = getenv("LD_DEBUG");
331 if (LD_DEBUG != nullptr) {
332 g_ld_debug_verbosity = atoi(LD_DEBUG);
333 }
334
335#if defined(__LP64__)
336 INFO("[ Android dynamic linker (64-bit) ]");
337#else
338 INFO("[ Android dynamic linker (32-bit) ]");
339#endif
340
341 // These should have been sanitized by __libc_init_AT_SECURE, but the test
342 // doesn't cost us anything.
343 const char* ldpath_env = nullptr;
344 const char* ldpreload_env = nullptr;
345 if (!getauxval(AT_SECURE)) {
346 ldpath_env = getenv("LD_LIBRARY_PATH");
347 if (ldpath_env != nullptr) {
348 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
349 }
350 ldpreload_env = getenv("LD_PRELOAD");
351 if (ldpreload_env != nullptr) {
352 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
353 }
354 }
355
Ryan Prichard8f639a42018-10-01 23:10:05 -0700356 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Ryan Prichard07440a82018-11-22 03:16:06 -0800357 get_executable_info();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700358
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700359 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000360
Ryan Prichard04896452018-08-20 17:44:42 -0700361 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700362 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700363 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700364 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700365 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700366 si->phdr = exe_info.phdr;
367 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700368 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
369 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
370 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700371 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700372 init_link_map_head(*si);
373
Vic Yang1bf62b22019-08-13 14:53:28 -0700374 set_bss_vma_name(si);
375
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700376 // Use the executable's PT_INTERP string as the solinker filename in the
377 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
378 // and if the paths for the linker are different, gdb will report that the
379 // PT_INTERP linker path was unloaded once the module list is initialized.
380 // There are three situations to handle:
381 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
382 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
383 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
384 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
385 somain->load_bias);
386 if (interp == nullptr) {
387 // This case can happen if the linker attempts to execute itself
388 // (e.g. "linker64 /system/bin/linker64").
389 interp = kFallbackLinkerPath;
390 }
391 solinker->set_realpath(interp);
392 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700393
Tamas Petz8d55d182020-02-24 14:15:25 +0100394#if defined(__aarch64__)
395 if (exe_to_load == nullptr) {
396 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
397 // Apply appropriate protections here if it is needed.
398 auto note_gnu_property = GnuPropertySection(somain);
399 if (note_gnu_property.IsBTICompatible() &&
400 (phdr_table_protect_segments(somain->phdr, somain->phnum, somain->load_bias,
401 &note_gnu_property) < 0)) {
402 __linker_error("error: can't protect segments for \"%s\": %s", exe_info.path.c_str(),
403 strerror(errno));
404 }
405 }
406#endif
407
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700408 // Register the main executable and the linker upfront to have
409 // gdb aware of them before loading the rest of the dependency
410 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700411 //
412 // gdb expects the linker to be in the debug shared object list.
413 // Without this, gdb has trouble locating the linker's ".text"
414 // and ".plt" sections. Gdb could also potentially use this to
415 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
416 //
417 insert_link_map_into_debug_map(&si->link_map_head);
418 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700419
Ryan Prichard07440a82018-11-22 03:16:06 -0800420 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700421
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700422 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800423
424 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700425 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700426 // We don't use async_safe_fatal here because we don't want a tombstone:
427 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800428 // investigations because some app's trying to launch an executable that
429 // hasn't worked in at least three years, and we've "helpfully" dropped a
430 // tombstone for them. The tombstone never provided any detail relevant to
431 // fixing the problem anyway, and the utility of drawing extra attention
432 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700433 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700434 "\"%s\": error: Android 5.0 and later only support "
435 "position-independent executables (-fPIE).\n",
436 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700437 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700438 }
439
440 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
441 parse_LD_LIBRARY_PATH(ldpath_env);
442 parse_LD_PRELOAD(ldpreload_env);
443
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700444 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700445
Elliott Hughesad2d0382017-07-31 11:43:34 -0700446 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700447
448 // add somain to global group
449 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900450 // ... and add it to all other linked namespaces
451 for (auto linked_ns : namespaces) {
452 if (linked_ns != &g_default_namespace) {
453 linked_ns->add_soinfo(somain);
454 somain->add_secondary_namespace(linked_ns);
455 }
456 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700457
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800458 linker_setup_exe_static_tls(g_argv[0]);
459
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700460 // Load ld_preloads and dependencies.
461 std::vector<const char*> needed_library_name_list;
462 size_t ld_preloads_count = 0;
463
464 for (const auto& ld_preload_name : g_ld_preload_names) {
465 needed_library_name_list.push_back(ld_preload_name.c_str());
466 ++ld_preloads_count;
467 }
468
469 for_each_dt_needed(si, [&](const char* name) {
470 needed_library_name_list.push_back(name);
471 });
472
473 const char** needed_library_names = &needed_library_name_list[0];
474 size_t needed_libraries_count = needed_library_name_list.size();
475
476 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800477 !find_libraries(&g_default_namespace,
478 si,
479 needed_library_names,
480 needed_libraries_count,
481 nullptr,
482 &g_ld_preloads,
483 ld_preloads_count,
484 RTLD_GLOBAL,
485 nullptr,
486 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900487 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700488 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700489 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800490 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700491 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700492 }
493 si->increment_ref_count();
494 }
495
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800496 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800497 __libc_init_main_thread_final();
498
Elliott Hughesad2d0382017-07-31 11:43:34 -0700499 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700500
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800501 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800502 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700503
504#if TIMING
505 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700506 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
507 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
508 static_cast<long long>(t1.tv_usec)) -
509 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
510 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700511#endif
512#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700513 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700514#endif
Ryan Prichard78cd2832019-10-25 17:46:43 -0700515#if TIMING || STATS
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700516 fflush(stdout);
517#endif
518
Vic Yangbb7e1232019-01-29 20:23:16 -0800519 // We are about to hand control over to the executable loaded. We don't want
520 // to leave dirty pages behind unnecessarily.
521 purge_unused_memory();
522
Ryan Prichard8f639a42018-10-01 23:10:05 -0700523 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700524 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
525 return entry;
526}
527
528/* Compute the load-bias of an existing executable. This shall only
529 * be used to compute the load bias of an executable or shared library
530 * that was loaded by the kernel itself.
531 *
532 * Input:
533 * elf -> address of ELF header, assumed to be at the start of the file.
534 * Return:
535 * load bias, i.e. add the value of any p_vaddr in the file to get
536 * the corresponding address in memory.
537 */
538static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
539 ElfW(Addr) offset = elf->e_phoff;
540 const ElfW(Phdr)* phdr_table =
541 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
542 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
543
544 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
545 if (phdr->p_type == PT_LOAD) {
546 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
547 }
548 }
549 return 0;
550}
551
Ryan Prichard9729f352018-07-13 22:40:26 -0700552/* Find the load bias and base address of an executable or shared object loaded
553 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
554 *
555 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
556 */
557static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
558 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
559 for (size_t i = 0; i < phdr_count; ++i) {
560 if (phdr_table[i].p_type == PT_PHDR) {
561 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
562 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
563 return;
564 }
565 }
566 async_safe_fatal("Could not find a PHDR: broken executable?");
567}
568
Vic Yang1bf62b22019-08-13 14:53:28 -0700569/*
570 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
571 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
572 * namely the linker itself and the main executable.
573 */
574static void set_bss_vma_name(soinfo* si) {
575 for (size_t i = 0; i < si->phnum; ++i) {
576 auto phdr = &si->phdr[i];
577
578 if (phdr->p_type != PT_LOAD) {
579 continue;
580 }
581
582 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
583 ElfW(Addr) seg_page_end = PAGE_END(seg_start + phdr->p_memsz);
584 ElfW(Addr) seg_file_end = PAGE_END(seg_start + phdr->p_filesz);
585
586 if (seg_page_end > seg_file_end) {
587 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
588 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
589 ".bss");
590 }
591 }
592}
593
Ryan Prichard249757b2019-11-01 17:18:28 -0700594// TODO: There is a similar ifunc resolver calling loop in libc_init_static.cpp, but that version
595// uses weak symbols, which don't work in the linker prior to its relocation. This version also
596// supports a load bias. When we stop supporting the gold linker in the NDK, then maybe we can use
597// non-weak definitions and merge the two loops.
598#if defined(USE_RELA)
599extern __LIBC_HIDDEN__ ElfW(Rela) __rela_iplt_start[], __rela_iplt_end[];
600
601static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
602 for (ElfW(Rela) *r = __rela_iplt_start; r != __rela_iplt_end; ++r) {
603 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
604 ElfW(Addr) resolver = r->r_addend + load_bias;
605 *offset = __bionic_call_ifunc_resolver(resolver);
606 }
607}
608#else
609extern __LIBC_HIDDEN__ ElfW(Rel) __rel_iplt_start[], __rel_iplt_end[];
610
611static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
612 for (ElfW(Rel) *r = __rel_iplt_start; r != __rel_iplt_end; ++r) {
613 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
614 ElfW(Addr) resolver = *offset + load_bias;
615 *offset = __bionic_call_ifunc_resolver(resolver);
616 }
617}
618#endif
619
Ryan Prichard94a8e852019-11-05 14:19:18 -0800620// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
621static void linker_memclr(void* dst, size_t cnt) {
622 for (size_t i = 0; i < cnt; ++i) {
623 reinterpret_cast<char*>(dst)[i] = '\0';
624 }
625}
626
Ryan Prichard1990ba52019-02-07 21:31:31 -0800627// Detect an attempt to run the linker on itself. e.g.:
628// /system/bin/linker64 /system/bin/linker64
629// Use priority-1 to run this constructor before other constructors.
630__attribute__((constructor(1))) static void detect_self_exec() {
631 // Normally, the linker initializes the auxv global before calling its
632 // constructors. If the linker loads itself, though, the first loader calls
633 // the second loader's constructors before calling __linker_init.
634 if (__libc_shared_globals()->auxv != nullptr) {
635 return;
636 }
637#if defined(__i386__)
638 // We don't have access to the auxv struct from here, so use the int 0x80
639 // fallback.
640 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
641#endif
642 __linker_error("error: linker cannot load itself\n");
643}
644
Ryan Prichard742982d2018-05-30 22:32:17 -0700645static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700646__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700647
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700648/*
649 * This is the entry point for the linker, called from begin.S. This
650 * method is responsible for fixing the linker's own relocations, and
651 * then calling __linker_init_post_relocation().
652 *
653 * Because this method is called before the linker has fixed it's own
654 * relocations, any attempt to reference an extern variable, extern
655 * function, or other GOT reference will generate a segfault.
656 */
657extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800658 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700659 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800660 bionic_tcb temp_tcb __attribute__((uninitialized));
661 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800662 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700663
Ryan Prichard8f639a42018-10-01 23:10:05 -0700664 // When the linker is run by itself (rather than as an interpreter for
665 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800666 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700667 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800668 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
669 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700670 ElfW(Addr) load_bias;
671 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800672 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700673 &linker_addr, &load_bias);
674 }
George Burgess IV70591002017-06-27 16:23:45 -0700675
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700676 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
677 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
678
Ryan Prichard249757b2019-11-01 17:18:28 -0700679 // string.h functions must not be used prior to calling the linker's ifunc resolvers.
680 const ElfW(Addr) load_bias = get_elf_exec_load_bias(elf_hdr);
681 call_ifunc_resolvers(load_bias);
682
Ryan Prichard04896452018-08-20 17:44:42 -0700683 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700684
Ryan Prichard04896452018-08-20 17:44:42 -0700685 tmp_linker_so.base = linker_addr;
686 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Ryan Prichard249757b2019-11-01 17:18:28 -0700687 tmp_linker_so.load_bias = load_bias;
Ryan Prichard04896452018-08-20 17:44:42 -0700688 tmp_linker_so.dynamic = nullptr;
689 tmp_linker_so.phdr = phdr;
690 tmp_linker_so.phnum = elf_hdr->e_phnum;
691 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700692
693 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700694 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800695 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 -0700696
Ryan Prichard04896452018-08-20 17:44:42 -0700697 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700698}
699
700/*
701 * This code is called after the linker has linked itself and fixed its own
702 * GOT. It is safe to make references to externs and other non-local data at
703 * this point. The compiler sometimes moves GOT references earlier in a
704 * function, so avoid inlining this function (http://b/80503879).
705 */
706static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700707__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800708 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800709 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700710
711 // We didn't protect the linker's RELRO pages in link_image because we
712 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700713 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700714
Vic Yang1bf62b22019-08-13 14:53:28 -0700715 // And we can set VMA name for the bss section now
716 set_bss_vma_name(&tmp_linker_so);
717
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700718 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800719 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700720
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700721 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700722 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700723
Ryan Prichard8f639a42018-10-01 23:10:05 -0700724 // When the linker is run directly rather than acting as PT_INTERP, parse
725 // arguments and determine the executable to load. When it's instead acting
726 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
727 // linker's _start.
728 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800729 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700730 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
731 // We're being asked to behave like ldd(1).
732 g_is_ldd = true;
733 exe_to_load = args.argv[2];
734 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700735 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700736 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
737 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700738 "\n"
739 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
740 "this program because it's the PT_INTERP of a dynamic executable.\n"
741 "\n"
742 "This program can also be run directly to load and run a dynamic executable. The\n"
743 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700744 "page-aligned offset.\n"
745 "\n"
746 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700747 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700748 _exit(EXIT_SUCCESS);
749 } else {
750 exe_to_load = args.argv[1];
751 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700752 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700753 }
754
Ryan Prichard8f639a42018-10-01 23:10:05 -0700755 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800756 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
757 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700758 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800759 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700760
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700761 // Initialize static variables. Note that in order to
762 // get correct libdl_info we need to call constructors
763 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700764 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700765 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700766
Ryan Prichard8f639a42018-10-01 23:10:05 -0700767 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700768
Elliott Hughes90f96b92019-05-09 15:56:39 -0700769 if (g_is_ldd) _exit(EXIT_SUCCESS);
770
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700771 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
772
773 // Return the address that the calling assembly stub should jump to.
774 return start_address;
775}