blob: 264923f1d465fb0f102819d7e44561a0c00a670f [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 Prichard45d13492019-01-03 02:51:30 -080040#include "linker_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070041#include "linker_utils.h"
42
Ryan Prichard249757b2019-11-01 17:18:28 -070043#include "private/bionic_auxv.h"
44#include "private/bionic_call_ifunc_resolver.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070045#include "private/bionic_globals.h"
46#include "private/bionic_tls.h"
47#include "private/KernelArgumentBlock.h"
48
Ryan Prichard8f639a42018-10-01 23:10:05 -070049#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070050#include "android-base/strings.h"
51#include "android-base/stringprintf.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070052
Christopher Ferris7a3681e2017-04-24 17:48:32 -070053#include <async_safe/log.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080054#include <bionic/libc_init_common.h>
Ryan Prichard45d13492019-01-03 02:51:30 -080055#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070056
Dimitry Ivanov3f660572016-09-09 10:00:39 -070057#include <vector>
58
Ryan Prichard8f639a42018-10-01 23:10:05 -070059__LIBC_HIDDEN__ extern "C" void _start();
Dimitry Ivanov3f660572016-09-09 10:00:39 -070060
61static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
62
Ryan Prichard9729f352018-07-13 22:40:26 -070063static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
64 ElfW(Addr)* base, ElfW(Addr)* load_bias);
65
Vic Yang1bf62b22019-08-13 14:53:28 -070066static void set_bss_vma_name(soinfo* si);
67
Dimitry Ivanov3f660572016-09-09 10:00:39 -070068// These should be preserved static to avoid emitting
69// RELATIVE relocations for the part of the code running
70// before linker links itself.
71
72// TODO (dimtiry): remove somain, rename solist to solist_head
73static soinfo* solist;
74static soinfo* sonext;
75static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070076static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020077static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070078
79void solist_add_soinfo(soinfo* si) {
80 sonext->next = si;
81 sonext = si;
82}
83
84bool solist_remove_soinfo(soinfo* si) {
85 soinfo *prev = nullptr, *trav;
86 for (trav = solist; trav != nullptr; trav = trav->next) {
87 if (trav == si) {
88 break;
89 }
90 prev = trav;
91 }
92
93 if (trav == nullptr) {
94 // si was not in solist
95 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
96 return false;
97 }
98
99 // prev will never be null, because the first entry in solist is
100 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700101 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700102 prev->next = si->next;
103 if (si == sonext) {
104 sonext = prev;
105 }
106
107 return true;
108}
109
110soinfo* solist_get_head() {
111 return solist;
112}
113
114soinfo* solist_get_somain() {
115 return somain;
116}
117
dimitry8b142562018-05-09 15:22:38 +0200118soinfo* solist_get_vdso() {
119 return vdso;
120}
121
Elliott Hughes90f96b92019-05-09 15:56:39 -0700122bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700123int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700124
125static std::vector<std::string> g_ld_preload_names;
126
127static std::vector<soinfo*> g_ld_preloads;
128
129static void parse_path(const char* path, const char* delimiters,
130 std::vector<std::string>* resolved_paths) {
131 std::vector<std::string> paths;
132 split_path(path, delimiters, &paths);
133 resolve_paths(paths, resolved_paths);
134}
135
136static void parse_LD_LIBRARY_PATH(const char* path) {
137 std::vector<std::string> ld_libary_paths;
138 parse_path(path, ":", &ld_libary_paths);
139 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
140}
141
142static void parse_LD_PRELOAD(const char* path) {
143 g_ld_preload_names.clear();
144 if (path != nullptr) {
145 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
146 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700147 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 -0700148 [](const std::string& s) { return s.empty(); }),
149 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700150 }
151}
152
153// An empty list of soinfos
154static soinfo_list_t g_empty_list;
155
Ryan Prichard07440a82018-11-22 03:16:06 -0800156static void add_vdso() {
157 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700158 if (ehdr_vdso == nullptr) {
159 return;
160 }
161
162 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
163
164 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
165 si->phnum = ehdr_vdso->e_phnum;
166 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
167 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
168 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
169
170 si->prelink_image();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400171 si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr, nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200172 // prevents accidental unloads...
173 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
174 si->set_linked();
175 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200176
177 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700178}
179
Ryan Prichard04896452018-08-20 17:44:42 -0700180// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700181// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
182// this function is called.
183static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700184 auto& map = info.link_map_head;
185 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700186 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700187 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700188}
189
190extern "C" int __system_properties_init(void);
191
Ryan Prichard8f639a42018-10-01 23:10:05 -0700192struct ExecutableInfo {
193 std::string path;
194 struct stat file_stat;
195 const ElfW(Phdr)* phdr;
196 size_t phdr_count;
197 ElfW(Addr) entry_point;
198};
199
Ryan Prichard07440a82018-11-22 03:16:06 -0800200static ExecutableInfo get_executable_info() {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700201 ExecutableInfo result = {};
202
Tom Cherry66bc4282018-11-08 13:40:52 -0800203 if (is_first_stage_init()) {
204 // /proc fs is not mounted when first stage init starts. Therefore we can't
205 // use /proc/self/exe for init.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700206 stat("/init", &result.file_stat);
Tom Cherry66bc4282018-11-08 13:40:52 -0800207
208 // /init may be a symlink, so try to read it as such.
209 char path[PATH_MAX];
210 ssize_t path_len = readlink("/init", path, sizeof(path));
211 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
212 result.path = "/init";
213 } else {
214 result.path = std::string(path, path_len);
215 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700216 } else {
217 // Stat "/proc/self/exe" instead of executable_path because
218 // the executable could be unlinked by this point and it should
219 // not cause a crash (see http://b/31084669)
220 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &result.file_stat)) != 0) {
221 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700222 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700223 char path[PATH_MAX];
224 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
225 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
226 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
227 }
228 result.path = std::string(path, path_len);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700229 }
230
Ryan Prichard07440a82018-11-22 03:16:06 -0800231 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
232 result.phdr_count = getauxval(AT_PHNUM);
233 result.entry_point = getauxval(AT_ENTRY);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700234 return result;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700235}
236
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800237#if defined(__LP64__)
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700238static char kFallbackLinkerPath[] = "/system/bin/linker64";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800239#else
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700240static char kFallbackLinkerPath[] = "/system/bin/linker";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800241#endif
242
Ryan Prichard8f639a42018-10-01 23:10:05 -0700243__printflike(1, 2)
244static void __linker_error(const char* fmt, ...) {
245 va_list ap;
dimitry04f7a792017-09-29 11:52:17 +0200246
Ryan Prichard8f639a42018-10-01 23:10:05 -0700247 va_start(ap, fmt);
248 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
249 va_end(ap);
250
251 va_start(ap, fmt);
252 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
253 va_end(ap);
254
dimitry04f7a792017-09-29 11:52:17 +0200255 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700256}
257
Ryan Prichard8f639a42018-10-01 23:10:05 -0700258static void __linker_cannot_link(const char* argv0) {
259 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s\n",
260 argv0,
261 linker_get_error_buffer());
262}
263
264// Load an executable. Normally the kernel has already loaded the executable when the linker
265// starts. The linker can be invoked directly on an executable, though, and then the linker must
266// load it. This function doesn't load dependencies or resolve relocations.
267static ExecutableInfo load_executable(const char* orig_path) {
268 ExecutableInfo result = {};
269
270 if (orig_path[0] != '/') {
271 __linker_error("error: expected absolute path: \"%s\"\n", orig_path);
272 }
273
274 off64_t file_offset;
275 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
276 if (fd.get() == -1) {
277 __linker_error("error: unable to open file \"%s\"\n", orig_path);
278 }
279
280 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
281 __linker_error("error: unable to stat \"%s\": %s\n", result.path.c_str(), strerror(errno));
282 }
283
284 ElfReader elf_reader;
285 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
286 __linker_error("error: %s\n", linker_get_error_buffer());
287 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400288 address_space_params address_space;
289 if (!elf_reader.Load(&address_space)) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700290 __linker_error("error: %s\n", linker_get_error_buffer());
291 }
292
293 result.phdr = elf_reader.loaded_phdr();
294 result.phdr_count = elf_reader.phdr_count();
295 result.entry_point = elf_reader.entry_point();
296 return result;
297}
298
299static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800300 ProtectedDataGuard guard;
301
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700302#if TIMING
303 struct timeval t0, t1;
304 gettimeofday(&t0, 0);
305#endif
306
307 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800308 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700309
310 // Initialize system properties
311 __system_properties_init(); // may use 'environ'
312
313 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700314 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700315
316 g_linker_logger.ResetState();
317
318 // Get a few environment variables.
319 const char* LD_DEBUG = getenv("LD_DEBUG");
320 if (LD_DEBUG != nullptr) {
321 g_ld_debug_verbosity = atoi(LD_DEBUG);
322 }
323
324#if defined(__LP64__)
325 INFO("[ Android dynamic linker (64-bit) ]");
326#else
327 INFO("[ Android dynamic linker (32-bit) ]");
328#endif
329
330 // These should have been sanitized by __libc_init_AT_SECURE, but the test
331 // doesn't cost us anything.
332 const char* ldpath_env = nullptr;
333 const char* ldpreload_env = nullptr;
334 if (!getauxval(AT_SECURE)) {
335 ldpath_env = getenv("LD_LIBRARY_PATH");
336 if (ldpath_env != nullptr) {
337 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
338 }
339 ldpreload_env = getenv("LD_PRELOAD");
340 if (ldpreload_env != nullptr) {
341 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
342 }
343 }
344
Ryan Prichard8f639a42018-10-01 23:10:05 -0700345 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Ryan Prichard07440a82018-11-22 03:16:06 -0800346 get_executable_info();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700347
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700348 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000349
Ryan Prichard04896452018-08-20 17:44:42 -0700350 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700351 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700352 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700353 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700354 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700355 si->phdr = exe_info.phdr;
356 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700357 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
358 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
359 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700360 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700361 init_link_map_head(*si);
362
Vic Yang1bf62b22019-08-13 14:53:28 -0700363 set_bss_vma_name(si);
364
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700365 // Use the executable's PT_INTERP string as the solinker filename in the
366 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
367 // and if the paths for the linker are different, gdb will report that the
368 // PT_INTERP linker path was unloaded once the module list is initialized.
369 // There are three situations to handle:
370 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
371 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
372 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
373 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
374 somain->load_bias);
375 if (interp == nullptr) {
376 // This case can happen if the linker attempts to execute itself
377 // (e.g. "linker64 /system/bin/linker64").
378 interp = kFallbackLinkerPath;
379 }
380 solinker->set_realpath(interp);
381 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700382
383 // Register the main executable and the linker upfront to have
384 // gdb aware of them before loading the rest of the dependency
385 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700386 //
387 // gdb expects the linker to be in the debug shared object list.
388 // Without this, gdb has trouble locating the linker's ".text"
389 // and ".plt" sections. Gdb could also potentially use this to
390 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
391 //
392 insert_link_map_into_debug_map(&si->link_map_head);
393 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700394
Ryan Prichard07440a82018-11-22 03:16:06 -0800395 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700396
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700397 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800398
399 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700400 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700401 // We don't use async_safe_fatal here because we don't want a tombstone:
402 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800403 // investigations because some app's trying to launch an executable that
404 // hasn't worked in at least three years, and we've "helpfully" dropped a
405 // tombstone for them. The tombstone never provided any detail relevant to
406 // fixing the problem anyway, and the utility of drawing extra attention
407 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700408 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700409 "\"%s\": error: Android 5.0 and later only support "
410 "position-independent executables (-fPIE).\n",
411 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700412 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700413 }
414
415 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
416 parse_LD_LIBRARY_PATH(ldpath_env);
417 parse_LD_PRELOAD(ldpreload_env);
418
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700419 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700420
Elliott Hughesad2d0382017-07-31 11:43:34 -0700421 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700422
423 // add somain to global group
424 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900425 // ... and add it to all other linked namespaces
426 for (auto linked_ns : namespaces) {
427 if (linked_ns != &g_default_namespace) {
428 linked_ns->add_soinfo(somain);
429 somain->add_secondary_namespace(linked_ns);
430 }
431 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700432
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800433 linker_setup_exe_static_tls(g_argv[0]);
434
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700435 // Load ld_preloads and dependencies.
436 std::vector<const char*> needed_library_name_list;
437 size_t ld_preloads_count = 0;
438
439 for (const auto& ld_preload_name : g_ld_preload_names) {
440 needed_library_name_list.push_back(ld_preload_name.c_str());
441 ++ld_preloads_count;
442 }
443
444 for_each_dt_needed(si, [&](const char* name) {
445 needed_library_name_list.push_back(name);
446 });
447
448 const char** needed_library_names = &needed_library_name_list[0];
449 size_t needed_libraries_count = needed_library_name_list.size();
450
451 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800452 !find_libraries(&g_default_namespace,
453 si,
454 needed_library_names,
455 needed_libraries_count,
456 nullptr,
457 &g_ld_preloads,
458 ld_preloads_count,
459 RTLD_GLOBAL,
460 nullptr,
461 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900462 true /* search_linked_namespaces */,
Jiyong Park02586a22017-05-20 01:01:24 +0900463 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700464 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700465 } else if (needed_libraries_count == 0) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400466 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700467 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700468 }
469 si->increment_ref_count();
470 }
471
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800472 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800473 __libc_init_main_thread_final();
474
Elliott Hughesad2d0382017-07-31 11:43:34 -0700475 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700476
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800477 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800478 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700479
480#if TIMING
481 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700482 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
483 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
484 static_cast<long long>(t1.tv_usec)) -
485 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
486 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700487#endif
488#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700489 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700490#endif
Ryan Prichard78cd2832019-10-25 17:46:43 -0700491#if TIMING || STATS
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700492 fflush(stdout);
493#endif
494
Vic Yangbb7e1232019-01-29 20:23:16 -0800495 // We are about to hand control over to the executable loaded. We don't want
496 // to leave dirty pages behind unnecessarily.
497 purge_unused_memory();
498
Ryan Prichard8f639a42018-10-01 23:10:05 -0700499 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700500 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
501 return entry;
502}
503
504/* Compute the load-bias of an existing executable. This shall only
505 * be used to compute the load bias of an executable or shared library
506 * that was loaded by the kernel itself.
507 *
508 * Input:
509 * elf -> address of ELF header, assumed to be at the start of the file.
510 * Return:
511 * load bias, i.e. add the value of any p_vaddr in the file to get
512 * the corresponding address in memory.
513 */
514static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
515 ElfW(Addr) offset = elf->e_phoff;
516 const ElfW(Phdr)* phdr_table =
517 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
518 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
519
520 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
521 if (phdr->p_type == PT_LOAD) {
522 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
523 }
524 }
525 return 0;
526}
527
Ryan Prichard9729f352018-07-13 22:40:26 -0700528/* Find the load bias and base address of an executable or shared object loaded
529 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
530 *
531 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
532 */
533static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
534 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
535 for (size_t i = 0; i < phdr_count; ++i) {
536 if (phdr_table[i].p_type == PT_PHDR) {
537 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
538 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
539 return;
540 }
541 }
542 async_safe_fatal("Could not find a PHDR: broken executable?");
543}
544
Vic Yang1bf62b22019-08-13 14:53:28 -0700545/*
546 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
547 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
548 * namely the linker itself and the main executable.
549 */
550static void set_bss_vma_name(soinfo* si) {
551 for (size_t i = 0; i < si->phnum; ++i) {
552 auto phdr = &si->phdr[i];
553
554 if (phdr->p_type != PT_LOAD) {
555 continue;
556 }
557
558 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
559 ElfW(Addr) seg_page_end = PAGE_END(seg_start + phdr->p_memsz);
560 ElfW(Addr) seg_file_end = PAGE_END(seg_start + phdr->p_filesz);
561
562 if (seg_page_end > seg_file_end) {
563 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
564 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
565 ".bss");
566 }
567 }
568}
569
Ryan Prichard249757b2019-11-01 17:18:28 -0700570// TODO: There is a similar ifunc resolver calling loop in libc_init_static.cpp, but that version
571// uses weak symbols, which don't work in the linker prior to its relocation. This version also
572// supports a load bias. When we stop supporting the gold linker in the NDK, then maybe we can use
573// non-weak definitions and merge the two loops.
574#if defined(USE_RELA)
575extern __LIBC_HIDDEN__ ElfW(Rela) __rela_iplt_start[], __rela_iplt_end[];
576
577static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
578 for (ElfW(Rela) *r = __rela_iplt_start; r != __rela_iplt_end; ++r) {
579 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
580 ElfW(Addr) resolver = r->r_addend + load_bias;
581 *offset = __bionic_call_ifunc_resolver(resolver);
582 }
583}
584#else
585extern __LIBC_HIDDEN__ ElfW(Rel) __rel_iplt_start[], __rel_iplt_end[];
586
587static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
588 for (ElfW(Rel) *r = __rel_iplt_start; r != __rel_iplt_end; ++r) {
589 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
590 ElfW(Addr) resolver = *offset + load_bias;
591 *offset = __bionic_call_ifunc_resolver(resolver);
592 }
593}
594#endif
595
Ryan Prichard1990ba52019-02-07 21:31:31 -0800596// Detect an attempt to run the linker on itself. e.g.:
597// /system/bin/linker64 /system/bin/linker64
598// Use priority-1 to run this constructor before other constructors.
599__attribute__((constructor(1))) static void detect_self_exec() {
600 // Normally, the linker initializes the auxv global before calling its
601 // constructors. If the linker loads itself, though, the first loader calls
602 // the second loader's constructors before calling __linker_init.
603 if (__libc_shared_globals()->auxv != nullptr) {
604 return;
605 }
606#if defined(__i386__)
607 // We don't have access to the auxv struct from here, so use the int 0x80
608 // fallback.
609 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
610#endif
611 __linker_error("error: linker cannot load itself\n");
612}
613
Ryan Prichard742982d2018-05-30 22:32:17 -0700614static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700615__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700616
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700617/*
618 * This is the entry point for the linker, called from begin.S. This
619 * method is responsible for fixing the linker's own relocations, and
620 * then calling __linker_init_post_relocation().
621 *
622 * Because this method is called before the linker has fixed it's own
623 * relocations, any attempt to reference an extern variable, extern
624 * function, or other GOT reference will generate a segfault.
625 */
626extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800627 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700628 KernelArgumentBlock args(raw_args);
Ryan Prichard45d13492019-01-03 02:51:30 -0800629 bionic_tcb temp_tcb = {};
630 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700631
Ryan Prichard8f639a42018-10-01 23:10:05 -0700632 // When the linker is run by itself (rather than as an interpreter for
633 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800634 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700635 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800636 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
637 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700638 ElfW(Addr) load_bias;
639 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800640 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700641 &linker_addr, &load_bias);
642 }
George Burgess IV70591002017-06-27 16:23:45 -0700643
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700644 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
645 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
646
Ryan Prichard249757b2019-11-01 17:18:28 -0700647 // string.h functions must not be used prior to calling the linker's ifunc resolvers.
648 const ElfW(Addr) load_bias = get_elf_exec_load_bias(elf_hdr);
649 call_ifunc_resolvers(load_bias);
650
Ryan Prichard04896452018-08-20 17:44:42 -0700651 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700652
Ryan Prichard04896452018-08-20 17:44:42 -0700653 tmp_linker_so.base = linker_addr;
654 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Ryan Prichard249757b2019-11-01 17:18:28 -0700655 tmp_linker_so.load_bias = load_bias;
Ryan Prichard04896452018-08-20 17:44:42 -0700656 tmp_linker_so.dynamic = nullptr;
657 tmp_linker_so.phdr = phdr;
658 tmp_linker_so.phnum = elf_hdr->e_phnum;
659 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700660
661 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700662 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700663
664 // This might not be obvious... The reasons why we pass g_empty_list
665 // in place of local_group here are (1) we do not really need it, because
666 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
667 // itself without having to look into local_group and (2) allocators
668 // are not yet initialized, and therefore we cannot use linked_list.push_*
669 // functions at this point.
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400670 if (!tmp_linker_so.link_image(g_empty_list, g_empty_list, nullptr, nullptr)) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700671
Ryan Prichard04896452018-08-20 17:44:42 -0700672 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700673}
674
675/*
676 * This code is called after the linker has linked itself and fixed its own
677 * GOT. It is safe to make references to externs and other non-local data at
678 * this point. The compiler sometimes moves GOT references earlier in a
679 * function, so avoid inlining this function (http://b/80503879).
680 */
681static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700682__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800683 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800684 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700685
686 // We didn't protect the linker's RELRO pages in link_image because we
687 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700688 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700689
Vic Yang1bf62b22019-08-13 14:53:28 -0700690 // And we can set VMA name for the bss section now
691 set_bss_vma_name(&tmp_linker_so);
692
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700693 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800694 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700695
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700696 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700697 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700698
Ryan Prichard8f639a42018-10-01 23:10:05 -0700699 // When the linker is run directly rather than acting as PT_INTERP, parse
700 // arguments and determine the executable to load. When it's instead acting
701 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
702 // linker's _start.
703 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800704 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700705 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
706 // We're being asked to behave like ldd(1).
707 g_is_ldd = true;
708 exe_to_load = args.argv[2];
709 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700710 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700711 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
712 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700713 "\n"
714 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
715 "this program because it's the PT_INTERP of a dynamic executable.\n"
716 "\n"
717 "This program can also be run directly to load and run a dynamic executable. The\n"
718 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700719 "page-aligned offset.\n"
720 "\n"
721 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700722 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700723 _exit(EXIT_SUCCESS);
724 } else {
725 exe_to_load = args.argv[1];
726 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700727 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700728 }
729
Ryan Prichard8f639a42018-10-01 23:10:05 -0700730 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800731 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
732 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700733 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800734 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700735
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700736 // Initialize static variables. Note that in order to
737 // get correct libdl_info we need to call constructors
738 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700739 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700740 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700741
Ryan Prichard8f639a42018-10-01 23:10:05 -0700742 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700743
Elliott Hughes90f96b92019-05-09 15:56:39 -0700744 if (g_is_ldd) _exit(EXIT_SUCCESS);
745
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700746 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
747
748 // Return the address that the calling assembly stub should jump to.
749 return start_address;
750}