blob: fd1592d33f68afbf2ae12bafe9efdb1ba99d9893 [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"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070035#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070036#include "linker_gdb_support.h"
37#include "linker_globals.h"
38#include "linker_phdr.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080039#include "linker_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070040#include "linker_utils.h"
41
42#include "private/bionic_globals.h"
43#include "private/bionic_tls.h"
44#include "private/KernelArgumentBlock.h"
45
Ryan Prichard8f639a42018-10-01 23:10:05 -070046#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070047#include "android-base/strings.h"
48#include "android-base/stringprintf.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080049#ifdef __ANDROID__
Josh Gao2a3b4fa2016-10-26 17:55:49 -070050#include "debuggerd/handler.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080051#endif
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.
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800314#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700315 debuggerd_callbacks_t callbacks = {
316 .get_abort_message = []() {
Ryan Prichard7752bcb2018-11-22 02:41:04 -0800317 return __libc_shared_globals()->abort_msg;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700318 },
319 .post_dump = &notify_gdb_of_libraries,
320 };
321 debuggerd_init(&callbacks);
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800322#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700323
324 g_linker_logger.ResetState();
325
326 // Get a few environment variables.
327 const char* LD_DEBUG = getenv("LD_DEBUG");
328 if (LD_DEBUG != nullptr) {
329 g_ld_debug_verbosity = atoi(LD_DEBUG);
330 }
331
332#if defined(__LP64__)
333 INFO("[ Android dynamic linker (64-bit) ]");
334#else
335 INFO("[ Android dynamic linker (32-bit) ]");
336#endif
337
338 // These should have been sanitized by __libc_init_AT_SECURE, but the test
339 // doesn't cost us anything.
340 const char* ldpath_env = nullptr;
341 const char* ldpreload_env = nullptr;
342 if (!getauxval(AT_SECURE)) {
343 ldpath_env = getenv("LD_LIBRARY_PATH");
344 if (ldpath_env != nullptr) {
345 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
346 }
347 ldpreload_env = getenv("LD_PRELOAD");
348 if (ldpreload_env != nullptr) {
349 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
350 }
351 }
352
Ryan Prichard8f639a42018-10-01 23:10:05 -0700353 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Ryan Prichard07440a82018-11-22 03:16:06 -0800354 get_executable_info();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700355
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700356 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000357
Ryan Prichard04896452018-08-20 17:44:42 -0700358 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700359 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700360 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700361 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700362 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700363 si->phdr = exe_info.phdr;
364 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700365 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
366 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
367 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700368 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700369 init_link_map_head(*si);
370
Vic Yang1bf62b22019-08-13 14:53:28 -0700371 set_bss_vma_name(si);
372
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700373 // Use the executable's PT_INTERP string as the solinker filename in the
374 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
375 // and if the paths for the linker are different, gdb will report that the
376 // PT_INTERP linker path was unloaded once the module list is initialized.
377 // There are three situations to handle:
378 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
379 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
380 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
381 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
382 somain->load_bias);
383 if (interp == nullptr) {
384 // This case can happen if the linker attempts to execute itself
385 // (e.g. "linker64 /system/bin/linker64").
386 interp = kFallbackLinkerPath;
387 }
388 solinker->set_realpath(interp);
389 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700390
391 // Register the main executable and the linker upfront to have
392 // gdb aware of them before loading the rest of the dependency
393 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700394 //
395 // gdb expects the linker to be in the debug shared object list.
396 // Without this, gdb has trouble locating the linker's ".text"
397 // and ".plt" sections. Gdb could also potentially use this to
398 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
399 //
400 insert_link_map_into_debug_map(&si->link_map_head);
401 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700402
Ryan Prichard07440a82018-11-22 03:16:06 -0800403 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700404
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700405 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800406
407 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700408 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700409 // We don't use async_safe_fatal here because we don't want a tombstone:
410 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800411 // investigations because some app's trying to launch an executable that
412 // hasn't worked in at least three years, and we've "helpfully" dropped a
413 // tombstone for them. The tombstone never provided any detail relevant to
414 // fixing the problem anyway, and the utility of drawing extra attention
415 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700416 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700417 "\"%s\": error: Android 5.0 and later only support "
418 "position-independent executables (-fPIE).\n",
419 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700420 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700421 }
422
423 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
424 parse_LD_LIBRARY_PATH(ldpath_env);
425 parse_LD_PRELOAD(ldpreload_env);
426
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700427 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700428
Elliott Hughesad2d0382017-07-31 11:43:34 -0700429 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700430
431 // add somain to global group
432 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900433 // ... and add it to all other linked namespaces
434 for (auto linked_ns : namespaces) {
435 if (linked_ns != &g_default_namespace) {
436 linked_ns->add_soinfo(somain);
437 somain->add_secondary_namespace(linked_ns);
438 }
439 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700440
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800441 linker_setup_exe_static_tls(g_argv[0]);
442
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700443 // Load ld_preloads and dependencies.
444 std::vector<const char*> needed_library_name_list;
445 size_t ld_preloads_count = 0;
446
447 for (const auto& ld_preload_name : g_ld_preload_names) {
448 needed_library_name_list.push_back(ld_preload_name.c_str());
449 ++ld_preloads_count;
450 }
451
452 for_each_dt_needed(si, [&](const char* name) {
453 needed_library_name_list.push_back(name);
454 });
455
456 const char** needed_library_names = &needed_library_name_list[0];
457 size_t needed_libraries_count = needed_library_name_list.size();
458
459 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800460 !find_libraries(&g_default_namespace,
461 si,
462 needed_library_names,
463 needed_libraries_count,
464 nullptr,
465 &g_ld_preloads,
466 ld_preloads_count,
467 RTLD_GLOBAL,
468 nullptr,
469 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900470 true /* search_linked_namespaces */,
Jiyong Park02586a22017-05-20 01:01:24 +0900471 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700472 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700473 } else if (needed_libraries_count == 0) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400474 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700475 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700476 }
477 si->increment_ref_count();
478 }
479
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800480 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800481 __libc_init_main_thread_final();
482
Elliott Hughesad2d0382017-07-31 11:43:34 -0700483 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700484
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800485 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800486 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700487
488#if TIMING
489 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700490 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
491 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
492 static_cast<long long>(t1.tv_usec)) -
493 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
494 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700495#endif
496#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700497 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700498#endif
499#if COUNT_PAGES
500 {
501 unsigned n;
502 unsigned i;
503 unsigned count = 0;
504 for (n = 0; n < 4096; n++) {
505 if (bitmask[n]) {
506 unsigned x = bitmask[n];
507#if defined(__LP64__)
508 for (i = 0; i < 32; i++) {
509#else
510 for (i = 0; i < 8; i++) {
511#endif
512 if (x & 1) {
513 count++;
514 }
515 x >>= 1;
516 }
517 }
518 }
519 PRINT("PAGES MODIFIED: %s: %d (%dKB)", g_argv[0], count, count * 4);
520 }
521#endif
522
523#if TIMING || STATS || COUNT_PAGES
524 fflush(stdout);
525#endif
526
Vic Yangbb7e1232019-01-29 20:23:16 -0800527 // We are about to hand control over to the executable loaded. We don't want
528 // to leave dirty pages behind unnecessarily.
529 purge_unused_memory();
530
Ryan Prichard8f639a42018-10-01 23:10:05 -0700531 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700532 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
533 return entry;
534}
535
536/* Compute the load-bias of an existing executable. This shall only
537 * be used to compute the load bias of an executable or shared library
538 * that was loaded by the kernel itself.
539 *
540 * Input:
541 * elf -> address of ELF header, assumed to be at the start of the file.
542 * Return:
543 * load bias, i.e. add the value of any p_vaddr in the file to get
544 * the corresponding address in memory.
545 */
546static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
547 ElfW(Addr) offset = elf->e_phoff;
548 const ElfW(Phdr)* phdr_table =
549 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
550 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
551
552 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
553 if (phdr->p_type == PT_LOAD) {
554 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
555 }
556 }
557 return 0;
558}
559
Ryan Prichard9729f352018-07-13 22:40:26 -0700560/* Find the load bias and base address of an executable or shared object loaded
561 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
562 *
563 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
564 */
565static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
566 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
567 for (size_t i = 0; i < phdr_count; ++i) {
568 if (phdr_table[i].p_type == PT_PHDR) {
569 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
570 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
571 return;
572 }
573 }
574 async_safe_fatal("Could not find a PHDR: broken executable?");
575}
576
Vic Yang1bf62b22019-08-13 14:53:28 -0700577/*
578 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
579 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
580 * namely the linker itself and the main executable.
581 */
582static void set_bss_vma_name(soinfo* si) {
583 for (size_t i = 0; i < si->phnum; ++i) {
584 auto phdr = &si->phdr[i];
585
586 if (phdr->p_type != PT_LOAD) {
587 continue;
588 }
589
590 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
591 ElfW(Addr) seg_page_end = PAGE_END(seg_start + phdr->p_memsz);
592 ElfW(Addr) seg_file_end = PAGE_END(seg_start + phdr->p_filesz);
593
594 if (seg_page_end > seg_file_end) {
595 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
596 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
597 ".bss");
598 }
599 }
600}
601
Ryan Prichard1990ba52019-02-07 21:31:31 -0800602// Detect an attempt to run the linker on itself. e.g.:
603// /system/bin/linker64 /system/bin/linker64
604// Use priority-1 to run this constructor before other constructors.
605__attribute__((constructor(1))) static void detect_self_exec() {
606 // Normally, the linker initializes the auxv global before calling its
607 // constructors. If the linker loads itself, though, the first loader calls
608 // the second loader's constructors before calling __linker_init.
609 if (__libc_shared_globals()->auxv != nullptr) {
610 return;
611 }
612#if defined(__i386__)
613 // We don't have access to the auxv struct from here, so use the int 0x80
614 // fallback.
615 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
616#endif
617 __linker_error("error: linker cannot load itself\n");
618}
619
Ryan Prichard742982d2018-05-30 22:32:17 -0700620static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700621__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700622
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700623/*
624 * This is the entry point for the linker, called from begin.S. This
625 * method is responsible for fixing the linker's own relocations, and
626 * then calling __linker_init_post_relocation().
627 *
628 * Because this method is called before the linker has fixed it's own
629 * relocations, any attempt to reference an extern variable, extern
630 * function, or other GOT reference will generate a segfault.
631 */
632extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800633 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700634 KernelArgumentBlock args(raw_args);
Ryan Prichard45d13492019-01-03 02:51:30 -0800635 bionic_tcb temp_tcb = {};
636 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700637
Ryan Prichard8f639a42018-10-01 23:10:05 -0700638 // When the linker is run by itself (rather than as an interpreter for
639 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800640 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700641 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800642 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
643 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700644 ElfW(Addr) load_bias;
645 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800646 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700647 &linker_addr, &load_bias);
648 }
George Burgess IV70591002017-06-27 16:23:45 -0700649
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700650 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
651 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
652
Ryan Prichard04896452018-08-20 17:44:42 -0700653 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700654
Ryan Prichard04896452018-08-20 17:44:42 -0700655 tmp_linker_so.base = linker_addr;
656 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
657 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
658 tmp_linker_so.dynamic = nullptr;
659 tmp_linker_so.phdr = phdr;
660 tmp_linker_so.phnum = elf_hdr->e_phnum;
661 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700662
663 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700664 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700665
666 // This might not be obvious... The reasons why we pass g_empty_list
667 // in place of local_group here are (1) we do not really need it, because
668 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
669 // itself without having to look into local_group and (2) allocators
670 // are not yet initialized, and therefore we cannot use linked_list.push_*
671 // functions at this point.
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400672 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 -0700673
Ryan Prichard04896452018-08-20 17:44:42 -0700674 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700675}
676
677/*
678 * This code is called after the linker has linked itself and fixed its own
679 * GOT. It is safe to make references to externs and other non-local data at
680 * this point. The compiler sometimes moves GOT references earlier in a
681 * function, so avoid inlining this function (http://b/80503879).
682 */
683static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700684__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800685 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800686 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700687
688 // We didn't protect the linker's RELRO pages in link_image because we
689 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700690 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700691
Vic Yang1bf62b22019-08-13 14:53:28 -0700692 // And we can set VMA name for the bss section now
693 set_bss_vma_name(&tmp_linker_so);
694
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700695 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800696 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700697
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700698 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700699 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700700
Ryan Prichard8f639a42018-10-01 23:10:05 -0700701 // When the linker is run directly rather than acting as PT_INTERP, parse
702 // arguments and determine the executable to load. When it's instead acting
703 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
704 // linker's _start.
705 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800706 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700707 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
708 // We're being asked to behave like ldd(1).
709 g_is_ldd = true;
710 exe_to_load = args.argv[2];
711 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700712 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700713 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
714 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700715 "\n"
716 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
717 "this program because it's the PT_INTERP of a dynamic executable.\n"
718 "\n"
719 "This program can also be run directly to load and run a dynamic executable. The\n"
720 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700721 "page-aligned offset.\n"
722 "\n"
723 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700724 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700725 _exit(EXIT_SUCCESS);
726 } else {
727 exe_to_load = args.argv[1];
728 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700729 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700730 }
731
Ryan Prichard8f639a42018-10-01 23:10:05 -0700732 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800733 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
734 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700735 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800736 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700737
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700738 // Initialize static variables. Note that in order to
739 // get correct libdl_info we need to call constructors
740 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700741 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700742 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700743
Ryan Prichard8f639a42018-10-01 23:10:05 -0700744 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700745
Elliott Hughes90f96b92019-05-09 15:56:39 -0700746 if (g_is_ldd) _exit(EXIT_SUCCESS);
747
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700748 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
749
750 // Return the address that the calling assembly stub should jump to.
751 return start_address;
752}