blob: 59e803665b51e5399e077c3e407468794e798a66 [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
Evgenii Stepanov8564b8d2020-12-15 13:55:32 -080069void __libc_init_mte(const void* phdr_start, size_t phdr_count, uintptr_t load_bias);
70
Dimitry Ivanov3f660572016-09-09 10:00:39 -070071// These should be preserved static to avoid emitting
72// RELATIVE relocations for the part of the code running
73// before linker links itself.
74
75// TODO (dimtiry): remove somain, rename solist to solist_head
76static soinfo* solist;
77static soinfo* sonext;
78static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070079static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020080static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070081
82void solist_add_soinfo(soinfo* si) {
83 sonext->next = si;
84 sonext = si;
85}
86
87bool solist_remove_soinfo(soinfo* si) {
88 soinfo *prev = nullptr, *trav;
89 for (trav = solist; trav != nullptr; trav = trav->next) {
90 if (trav == si) {
91 break;
92 }
93 prev = trav;
94 }
95
96 if (trav == nullptr) {
97 // si was not in solist
98 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
99 return false;
100 }
101
102 // prev will never be null, because the first entry in solist is
103 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700104 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700105 prev->next = si->next;
106 if (si == sonext) {
107 sonext = prev;
108 }
109
110 return true;
111}
112
113soinfo* solist_get_head() {
114 return solist;
115}
116
117soinfo* solist_get_somain() {
118 return somain;
119}
120
dimitry8b142562018-05-09 15:22:38 +0200121soinfo* solist_get_vdso() {
122 return vdso;
123}
124
Elliott Hughes90f96b92019-05-09 15:56:39 -0700125bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700126int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700127
128static std::vector<std::string> g_ld_preload_names;
129
130static std::vector<soinfo*> g_ld_preloads;
131
132static void parse_path(const char* path, const char* delimiters,
133 std::vector<std::string>* resolved_paths) {
134 std::vector<std::string> paths;
135 split_path(path, delimiters, &paths);
136 resolve_paths(paths, resolved_paths);
137}
138
139static void parse_LD_LIBRARY_PATH(const char* path) {
140 std::vector<std::string> ld_libary_paths;
141 parse_path(path, ":", &ld_libary_paths);
142 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
143}
144
145static void parse_LD_PRELOAD(const char* path) {
146 g_ld_preload_names.clear();
147 if (path != nullptr) {
148 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
149 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700150 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 -0700151 [](const std::string& s) { return s.empty(); }),
152 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700153 }
154}
155
156// An empty list of soinfos
157static soinfo_list_t g_empty_list;
158
Ryan Prichard07440a82018-11-22 03:16:06 -0800159static void add_vdso() {
160 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700161 if (ehdr_vdso == nullptr) {
162 return;
163 }
164
165 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
166
167 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
168 si->phnum = ehdr_vdso->e_phnum;
169 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
170 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
171 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
172
173 si->prelink_image();
Ryan Prichard339ecef2020-01-02 16:36:06 -0800174 si->link_image(SymbolLookupList(si), si, nullptr, nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200175 // prevents accidental unloads...
176 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
177 si->set_linked();
178 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200179
180 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700181}
182
Ryan Prichard04896452018-08-20 17:44:42 -0700183// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700184// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
185// this function is called.
186static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700187 auto& map = info.link_map_head;
188 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700189 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700190 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700191}
192
193extern "C" int __system_properties_init(void);
194
Ryan Prichard8f639a42018-10-01 23:10:05 -0700195struct ExecutableInfo {
196 std::string path;
197 struct stat file_stat;
198 const ElfW(Phdr)* phdr;
199 size_t phdr_count;
200 ElfW(Addr) entry_point;
201};
202
Ryan Prichard07440a82018-11-22 03:16:06 -0800203static ExecutableInfo get_executable_info() {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700204 ExecutableInfo result = {};
205
Tom Cherry66bc4282018-11-08 13:40:52 -0800206 if (is_first_stage_init()) {
207 // /proc fs is not mounted when first stage init starts. Therefore we can't
208 // use /proc/self/exe for init.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700209 stat("/init", &result.file_stat);
Tom Cherry66bc4282018-11-08 13:40:52 -0800210
211 // /init may be a symlink, so try to read it as such.
212 char path[PATH_MAX];
213 ssize_t path_len = readlink("/init", path, sizeof(path));
214 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
215 result.path = "/init";
216 } else {
217 result.path = std::string(path, path_len);
218 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700219 } else {
220 // Stat "/proc/self/exe" instead of executable_path because
221 // the executable could be unlinked by this point and it should
222 // not cause a crash (see http://b/31084669)
223 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &result.file_stat)) != 0) {
224 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700225 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700226 char path[PATH_MAX];
227 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
228 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
229 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
230 }
231 result.path = std::string(path, path_len);
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
331 // Get a few environment variables.
332 const char* LD_DEBUG = getenv("LD_DEBUG");
333 if (LD_DEBUG != nullptr) {
334 g_ld_debug_verbosity = atoi(LD_DEBUG);
335 }
336
337#if defined(__LP64__)
338 INFO("[ Android dynamic linker (64-bit) ]");
339#else
340 INFO("[ Android dynamic linker (32-bit) ]");
341#endif
342
343 // These should have been sanitized by __libc_init_AT_SECURE, but the test
344 // doesn't cost us anything.
345 const char* ldpath_env = nullptr;
346 const char* ldpreload_env = nullptr;
347 if (!getauxval(AT_SECURE)) {
348 ldpath_env = getenv("LD_LIBRARY_PATH");
349 if (ldpath_env != nullptr) {
350 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
351 }
352 ldpreload_env = getenv("LD_PRELOAD");
353 if (ldpreload_env != nullptr) {
354 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
355 }
356 }
357
Ryan Prichard8f639a42018-10-01 23:10:05 -0700358 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Ryan Prichard07440a82018-11-22 03:16:06 -0800359 get_executable_info();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700360
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700361 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000362
Ryan Prichard04896452018-08-20 17:44:42 -0700363 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700364 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700365 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700366 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700367 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700368 si->phdr = exe_info.phdr;
369 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700370 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
371 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
372 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700373 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700374 init_link_map_head(*si);
375
Vic Yang1bf62b22019-08-13 14:53:28 -0700376 set_bss_vma_name(si);
377
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700378 // Use the executable's PT_INTERP string as the solinker filename in the
379 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
380 // and if the paths for the linker are different, gdb will report that the
381 // PT_INTERP linker path was unloaded once the module list is initialized.
382 // There are three situations to handle:
383 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
384 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
385 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
386 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
387 somain->load_bias);
388 if (interp == nullptr) {
389 // This case can happen if the linker attempts to execute itself
390 // (e.g. "linker64 /system/bin/linker64").
391 interp = kFallbackLinkerPath;
392 }
393 solinker->set_realpath(interp);
394 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700395
Tamas Petz8d55d182020-02-24 14:15:25 +0100396#if defined(__aarch64__)
397 if (exe_to_load == nullptr) {
398 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
399 // Apply appropriate protections here if it is needed.
400 auto note_gnu_property = GnuPropertySection(somain);
401 if (note_gnu_property.IsBTICompatible() &&
402 (phdr_table_protect_segments(somain->phdr, somain->phnum, somain->load_bias,
403 &note_gnu_property) < 0)) {
404 __linker_error("error: can't protect segments for \"%s\": %s", exe_info.path.c_str(),
405 strerror(errno));
406 }
407 }
Evgenii Stepanov8564b8d2020-12-15 13:55:32 -0800408
409 __libc_init_mte(somain->phdr, somain->phnum, somain->load_bias);
Tamas Petz8d55d182020-02-24 14:15:25 +0100410#endif
411
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700412 // Register the main executable and the linker upfront to have
413 // gdb aware of them before loading the rest of the dependency
414 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700415 //
416 // gdb expects the linker to be in the debug shared object list.
417 // Without this, gdb has trouble locating the linker's ".text"
418 // and ".plt" sections. Gdb could also potentially use this to
419 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
420 //
421 insert_link_map_into_debug_map(&si->link_map_head);
422 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700423
Ryan Prichard07440a82018-11-22 03:16:06 -0800424 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700425
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700426 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800427
428 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700429 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700430 // We don't use async_safe_fatal here because we don't want a tombstone:
431 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800432 // investigations because some app's trying to launch an executable that
433 // hasn't worked in at least three years, and we've "helpfully" dropped a
434 // tombstone for them. The tombstone never provided any detail relevant to
435 // fixing the problem anyway, and the utility of drawing extra attention
436 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700437 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700438 "\"%s\": error: Android 5.0 and later only support "
439 "position-independent executables (-fPIE).\n",
440 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700441 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700442 }
443
444 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
445 parse_LD_LIBRARY_PATH(ldpath_env);
446 parse_LD_PRELOAD(ldpreload_env);
447
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700448 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700449
Elliott Hughesad2d0382017-07-31 11:43:34 -0700450 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700451
452 // add somain to global group
453 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900454 // ... and add it to all other linked namespaces
455 for (auto linked_ns : namespaces) {
456 if (linked_ns != &g_default_namespace) {
457 linked_ns->add_soinfo(somain);
458 somain->add_secondary_namespace(linked_ns);
459 }
460 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700461
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800462 linker_setup_exe_static_tls(g_argv[0]);
463
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700464 // Load ld_preloads and dependencies.
465 std::vector<const char*> needed_library_name_list;
466 size_t ld_preloads_count = 0;
467
468 for (const auto& ld_preload_name : g_ld_preload_names) {
469 needed_library_name_list.push_back(ld_preload_name.c_str());
470 ++ld_preloads_count;
471 }
472
473 for_each_dt_needed(si, [&](const char* name) {
474 needed_library_name_list.push_back(name);
475 });
476
477 const char** needed_library_names = &needed_library_name_list[0];
478 size_t needed_libraries_count = needed_library_name_list.size();
479
480 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800481 !find_libraries(&g_default_namespace,
482 si,
483 needed_library_names,
484 needed_libraries_count,
485 nullptr,
486 &g_ld_preloads,
487 ld_preloads_count,
488 RTLD_GLOBAL,
489 nullptr,
490 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900491 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700492 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700493 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800494 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700495 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700496 }
497 si->increment_ref_count();
498 }
499
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800500 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800501 __libc_init_main_thread_final();
502
Elliott Hughesad2d0382017-07-31 11:43:34 -0700503 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700504
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800505 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800506 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700507
508#if TIMING
509 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700510 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
511 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
512 static_cast<long long>(t1.tv_usec)) -
513 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
514 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700515#endif
516#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700517 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700518#endif
Ryan Prichard78cd2832019-10-25 17:46:43 -0700519#if TIMING || STATS
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700520 fflush(stdout);
521#endif
522
Vic Yangbb7e1232019-01-29 20:23:16 -0800523 // We are about to hand control over to the executable loaded. We don't want
524 // to leave dirty pages behind unnecessarily.
525 purge_unused_memory();
526
Ryan Prichard8f639a42018-10-01 23:10:05 -0700527 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700528 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
529 return entry;
530}
531
532/* Compute the load-bias of an existing executable. This shall only
533 * be used to compute the load bias of an executable or shared library
534 * that was loaded by the kernel itself.
535 *
536 * Input:
537 * elf -> address of ELF header, assumed to be at the start of the file.
538 * Return:
539 * load bias, i.e. add the value of any p_vaddr in the file to get
540 * the corresponding address in memory.
541 */
542static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
543 ElfW(Addr) offset = elf->e_phoff;
544 const ElfW(Phdr)* phdr_table =
545 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
546 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
547
548 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
549 if (phdr->p_type == PT_LOAD) {
550 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
551 }
552 }
553 return 0;
554}
555
Ryan Prichard9729f352018-07-13 22:40:26 -0700556/* Find the load bias and base address of an executable or shared object loaded
557 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
558 *
559 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
560 */
561static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
562 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
563 for (size_t i = 0; i < phdr_count; ++i) {
564 if (phdr_table[i].p_type == PT_PHDR) {
565 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
566 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
567 return;
568 }
569 }
570 async_safe_fatal("Could not find a PHDR: broken executable?");
571}
572
Vic Yang1bf62b22019-08-13 14:53:28 -0700573/*
574 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
575 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
576 * namely the linker itself and the main executable.
577 */
578static void set_bss_vma_name(soinfo* si) {
579 for (size_t i = 0; i < si->phnum; ++i) {
580 auto phdr = &si->phdr[i];
581
582 if (phdr->p_type != PT_LOAD) {
583 continue;
584 }
585
586 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
587 ElfW(Addr) seg_page_end = PAGE_END(seg_start + phdr->p_memsz);
588 ElfW(Addr) seg_file_end = PAGE_END(seg_start + phdr->p_filesz);
589
590 if (seg_page_end > seg_file_end) {
591 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
592 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
593 ".bss");
594 }
595 }
596}
597
Ryan Prichard249757b2019-11-01 17:18:28 -0700598// TODO: There is a similar ifunc resolver calling loop in libc_init_static.cpp, but that version
599// uses weak symbols, which don't work in the linker prior to its relocation. This version also
600// supports a load bias. When we stop supporting the gold linker in the NDK, then maybe we can use
601// non-weak definitions and merge the two loops.
602#if defined(USE_RELA)
603extern __LIBC_HIDDEN__ ElfW(Rela) __rela_iplt_start[], __rela_iplt_end[];
604
605static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
606 for (ElfW(Rela) *r = __rela_iplt_start; r != __rela_iplt_end; ++r) {
607 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
608 ElfW(Addr) resolver = r->r_addend + load_bias;
609 *offset = __bionic_call_ifunc_resolver(resolver);
610 }
611}
612#else
613extern __LIBC_HIDDEN__ ElfW(Rel) __rel_iplt_start[], __rel_iplt_end[];
614
615static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
616 for (ElfW(Rel) *r = __rel_iplt_start; r != __rel_iplt_end; ++r) {
617 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
618 ElfW(Addr) resolver = *offset + load_bias;
619 *offset = __bionic_call_ifunc_resolver(resolver);
620 }
621}
622#endif
623
Ryan Prichard94a8e852019-11-05 14:19:18 -0800624// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
625static void linker_memclr(void* dst, size_t cnt) {
626 for (size_t i = 0; i < cnt; ++i) {
627 reinterpret_cast<char*>(dst)[i] = '\0';
628 }
629}
630
Ryan Prichard1990ba52019-02-07 21:31:31 -0800631// Detect an attempt to run the linker on itself. e.g.:
632// /system/bin/linker64 /system/bin/linker64
633// Use priority-1 to run this constructor before other constructors.
634__attribute__((constructor(1))) static void detect_self_exec() {
635 // Normally, the linker initializes the auxv global before calling its
636 // constructors. If the linker loads itself, though, the first loader calls
637 // the second loader's constructors before calling __linker_init.
638 if (__libc_shared_globals()->auxv != nullptr) {
639 return;
640 }
641#if defined(__i386__)
642 // We don't have access to the auxv struct from here, so use the int 0x80
643 // fallback.
644 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
645#endif
646 __linker_error("error: linker cannot load itself\n");
647}
648
Ryan Prichard742982d2018-05-30 22:32:17 -0700649static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700650__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700651
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700652/*
653 * This is the entry point for the linker, called from begin.S. This
654 * method is responsible for fixing the linker's own relocations, and
655 * then calling __linker_init_post_relocation().
656 *
657 * Because this method is called before the linker has fixed it's own
658 * relocations, any attempt to reference an extern variable, extern
659 * function, or other GOT reference will generate a segfault.
660 */
661extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800662 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700663 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800664 bionic_tcb temp_tcb __attribute__((uninitialized));
665 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800666 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700667
Ryan Prichard8f639a42018-10-01 23:10:05 -0700668 // When the linker is run by itself (rather than as an interpreter for
669 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800670 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700671 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800672 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
673 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700674 ElfW(Addr) load_bias;
675 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800676 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700677 &linker_addr, &load_bias);
678 }
George Burgess IV70591002017-06-27 16:23:45 -0700679
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700680 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
681 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
682
Ryan Prichard249757b2019-11-01 17:18:28 -0700683 // string.h functions must not be used prior to calling the linker's ifunc resolvers.
684 const ElfW(Addr) load_bias = get_elf_exec_load_bias(elf_hdr);
685 call_ifunc_resolvers(load_bias);
686
Ryan Prichard04896452018-08-20 17:44:42 -0700687 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700688
Ryan Prichard04896452018-08-20 17:44:42 -0700689 tmp_linker_so.base = linker_addr;
690 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Ryan Prichard249757b2019-11-01 17:18:28 -0700691 tmp_linker_so.load_bias = load_bias;
Ryan Prichard04896452018-08-20 17:44:42 -0700692 tmp_linker_so.dynamic = nullptr;
693 tmp_linker_so.phdr = phdr;
694 tmp_linker_so.phnum = elf_hdr->e_phnum;
695 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700696
697 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700698 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800699 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 -0700700
Ryan Prichard04896452018-08-20 17:44:42 -0700701 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700702}
703
704/*
705 * This code is called after the linker has linked itself and fixed its own
706 * GOT. It is safe to make references to externs and other non-local data at
707 * this point. The compiler sometimes moves GOT references earlier in a
708 * function, so avoid inlining this function (http://b/80503879).
709 */
710static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700711__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800712 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800713 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700714
715 // We didn't protect the linker's RELRO pages in link_image because we
716 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700717 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700718
Vic Yang1bf62b22019-08-13 14:53:28 -0700719 // And we can set VMA name for the bss section now
720 set_bss_vma_name(&tmp_linker_so);
721
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700722 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800723 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700724
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700725 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700726 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700727
Ryan Prichard8f639a42018-10-01 23:10:05 -0700728 // When the linker is run directly rather than acting as PT_INTERP, parse
729 // arguments and determine the executable to load. When it's instead acting
730 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
731 // linker's _start.
732 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800733 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700734 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
735 // We're being asked to behave like ldd(1).
736 g_is_ldd = true;
737 exe_to_load = args.argv[2];
738 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700739 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700740 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
741 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700742 "\n"
743 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
744 "this program because it's the PT_INTERP of a dynamic executable.\n"
745 "\n"
746 "This program can also be run directly to load and run a dynamic executable. The\n"
747 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700748 "page-aligned offset.\n"
749 "\n"
750 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700751 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700752 _exit(EXIT_SUCCESS);
753 } else {
754 exe_to_load = args.argv[1];
755 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700756 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700757 }
758
Ryan Prichard8f639a42018-10-01 23:10:05 -0700759 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800760 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
761 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700762 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800763 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700764
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700765 // Initialize static variables. Note that in order to
766 // get correct libdl_info we need to call constructors
767 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700768 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700769 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700770
Ryan Prichard8f639a42018-10-01 23:10:05 -0700771 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700772
Elliott Hughes90f96b92019-05-09 15:56:39 -0700773 if (g_is_ldd) _exit(EXIT_SUCCESS);
774
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700775 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
776
777 // Return the address that the calling assembly stub should jump to.
778 return start_address;
779}