blob: f5760231abfec01734f187d5fb9b72c037b01926 [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
Dimitry Ivanov3f660572016-09-09 10:00:39 -070066// These should be preserved static to avoid emitting
67// RELATIVE relocations for the part of the code running
68// before linker links itself.
69
70// TODO (dimtiry): remove somain, rename solist to solist_head
71static soinfo* solist;
72static soinfo* sonext;
73static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070074static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020075static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070076
77void solist_add_soinfo(soinfo* si) {
78 sonext->next = si;
79 sonext = si;
80}
81
82bool solist_remove_soinfo(soinfo* si) {
83 soinfo *prev = nullptr, *trav;
84 for (trav = solist; trav != nullptr; trav = trav->next) {
85 if (trav == si) {
86 break;
87 }
88 prev = trav;
89 }
90
91 if (trav == nullptr) {
92 // si was not in solist
93 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
94 return false;
95 }
96
97 // prev will never be null, because the first entry in solist is
98 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -070099 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700100 prev->next = si->next;
101 if (si == sonext) {
102 sonext = prev;
103 }
104
105 return true;
106}
107
108soinfo* solist_get_head() {
109 return solist;
110}
111
112soinfo* solist_get_somain() {
113 return somain;
114}
115
dimitry8b142562018-05-09 15:22:38 +0200116soinfo* solist_get_vdso() {
117 return vdso;
118}
119
Elliott Hughes90f96b92019-05-09 15:56:39 -0700120bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700121int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700122
123static std::vector<std::string> g_ld_preload_names;
124
125static std::vector<soinfo*> g_ld_preloads;
126
127static void parse_path(const char* path, const char* delimiters,
128 std::vector<std::string>* resolved_paths) {
129 std::vector<std::string> paths;
130 split_path(path, delimiters, &paths);
131 resolve_paths(paths, resolved_paths);
132}
133
134static void parse_LD_LIBRARY_PATH(const char* path) {
135 std::vector<std::string> ld_libary_paths;
136 parse_path(path, ":", &ld_libary_paths);
137 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
138}
139
140static void parse_LD_PRELOAD(const char* path) {
141 g_ld_preload_names.clear();
142 if (path != nullptr) {
143 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
144 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700145 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 -0700146 [](const std::string& s) { return s.empty(); }),
147 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700148 }
149}
150
151// An empty list of soinfos
152static soinfo_list_t g_empty_list;
153
Ryan Prichard07440a82018-11-22 03:16:06 -0800154static void add_vdso() {
155 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700156 if (ehdr_vdso == nullptr) {
157 return;
158 }
159
160 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
161
162 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
163 si->phnum = ehdr_vdso->e_phnum;
164 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
165 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
166 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
167
168 si->prelink_image();
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400169 si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr, nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200170 // prevents accidental unloads...
171 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
172 si->set_linked();
173 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200174
175 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700176}
177
Ryan Prichard04896452018-08-20 17:44:42 -0700178// Initializes an soinfo's link_map_head field using other fields from the
179// soinfo (phdr, phnum, load_bias).
180static void init_link_map_head(soinfo& info, const char* linker_path) {
181 auto& map = info.link_map_head;
182 map.l_addr = info.load_bias;
183 map.l_name = const_cast<char*>(linker_path);
184 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700185}
186
187extern "C" int __system_properties_init(void);
188
Ryan Prichard8f639a42018-10-01 23:10:05 -0700189struct ExecutableInfo {
190 std::string path;
191 struct stat file_stat;
192 const ElfW(Phdr)* phdr;
193 size_t phdr_count;
194 ElfW(Addr) entry_point;
195};
196
Ryan Prichard07440a82018-11-22 03:16:06 -0800197static ExecutableInfo get_executable_info() {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700198 ExecutableInfo result = {};
199
Tom Cherry66bc4282018-11-08 13:40:52 -0800200 if (is_first_stage_init()) {
201 // /proc fs is not mounted when first stage init starts. Therefore we can't
202 // use /proc/self/exe for init.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700203 stat("/init", &result.file_stat);
Tom Cherry66bc4282018-11-08 13:40:52 -0800204
205 // /init may be a symlink, so try to read it as such.
206 char path[PATH_MAX];
207 ssize_t path_len = readlink("/init", path, sizeof(path));
208 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
209 result.path = "/init";
210 } else {
211 result.path = std::string(path, path_len);
212 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700213 } else {
214 // Stat "/proc/self/exe" instead of executable_path because
215 // the executable could be unlinked by this point and it should
216 // not cause a crash (see http://b/31084669)
217 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &result.file_stat)) != 0) {
218 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700219 }
Ryan Prichard8f639a42018-10-01 23:10:05 -0700220 char path[PATH_MAX];
221 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
222 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
223 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
224 }
225 result.path = std::string(path, path_len);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700226 }
227
Ryan Prichard07440a82018-11-22 03:16:06 -0800228 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
229 result.phdr_count = getauxval(AT_PHNUM);
230 result.entry_point = getauxval(AT_ENTRY);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700231 return result;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700232}
233
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800234#if defined(__LP64__)
235static char kLinkerPath[] = "/system/bin/linker64";
236#else
237static char kLinkerPath[] = "/system/bin/linker";
238#endif
239
Ryan Prichard8f639a42018-10-01 23:10:05 -0700240__printflike(1, 2)
241static void __linker_error(const char* fmt, ...) {
242 va_list ap;
dimitry04f7a792017-09-29 11:52:17 +0200243
Ryan Prichard8f639a42018-10-01 23:10:05 -0700244 va_start(ap, fmt);
245 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
246 va_end(ap);
247
248 va_start(ap, fmt);
249 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
250 va_end(ap);
251
dimitry04f7a792017-09-29 11:52:17 +0200252 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700253}
254
Ryan Prichard8f639a42018-10-01 23:10:05 -0700255static void __linker_cannot_link(const char* argv0) {
256 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s\n",
257 argv0,
258 linker_get_error_buffer());
259}
260
261// Load an executable. Normally the kernel has already loaded the executable when the linker
262// starts. The linker can be invoked directly on an executable, though, and then the linker must
263// load it. This function doesn't load dependencies or resolve relocations.
264static ExecutableInfo load_executable(const char* orig_path) {
265 ExecutableInfo result = {};
266
267 if (orig_path[0] != '/') {
268 __linker_error("error: expected absolute path: \"%s\"\n", orig_path);
269 }
270
271 off64_t file_offset;
272 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
273 if (fd.get() == -1) {
274 __linker_error("error: unable to open file \"%s\"\n", orig_path);
275 }
276
277 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
278 __linker_error("error: unable to stat \"%s\": %s\n", result.path.c_str(), strerror(errno));
279 }
280
281 ElfReader elf_reader;
282 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
283 __linker_error("error: %s\n", linker_get_error_buffer());
284 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400285 address_space_params address_space;
286 if (!elf_reader.Load(&address_space)) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700287 __linker_error("error: %s\n", linker_get_error_buffer());
288 }
289
290 result.phdr = elf_reader.loaded_phdr();
291 result.phdr_count = elf_reader.phdr_count();
292 result.entry_point = elf_reader.entry_point();
293 return result;
294}
295
296static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800297 ProtectedDataGuard guard;
298
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700299#if TIMING
300 struct timeval t0, t1;
301 gettimeofday(&t0, 0);
302#endif
303
304 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800305 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700306
307 // Initialize system properties
308 __system_properties_init(); // may use 'environ'
309
310 // Register the debuggerd signal handler.
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800311#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700312 debuggerd_callbacks_t callbacks = {
313 .get_abort_message = []() {
Ryan Prichard7752bcb2018-11-22 02:41:04 -0800314 return __libc_shared_globals()->abort_msg;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700315 },
316 .post_dump = &notify_gdb_of_libraries,
317 };
318 debuggerd_init(&callbacks);
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800319#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700320
321 g_linker_logger.ResetState();
322
323 // Get a few environment variables.
324 const char* LD_DEBUG = getenv("LD_DEBUG");
325 if (LD_DEBUG != nullptr) {
326 g_ld_debug_verbosity = atoi(LD_DEBUG);
327 }
328
329#if defined(__LP64__)
330 INFO("[ Android dynamic linker (64-bit) ]");
331#else
332 INFO("[ Android dynamic linker (32-bit) ]");
333#endif
334
335 // These should have been sanitized by __libc_init_AT_SECURE, but the test
336 // doesn't cost us anything.
337 const char* ldpath_env = nullptr;
338 const char* ldpreload_env = nullptr;
339 if (!getauxval(AT_SECURE)) {
340 ldpath_env = getenv("LD_LIBRARY_PATH");
341 if (ldpath_env != nullptr) {
342 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
343 }
344 ldpreload_env = getenv("LD_PRELOAD");
345 if (ldpreload_env != nullptr) {
346 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
347 }
348 }
349
Ryan Prichard8f639a42018-10-01 23:10:05 -0700350 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Ryan Prichard07440a82018-11-22 03:16:06 -0800351 get_executable_info();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700352
353 // Assign to a static variable for the sake of the debug map, which needs
354 // a C-style string to last until the program exits.
355 static std::string exe_path = exe_info.path;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700356
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000357 INFO("[ Linking executable \"%s\" ]", exe_path.c_str());
358
Ryan Prichard04896452018-08-20 17:44:42 -0700359 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700360 soinfo* si = soinfo_alloc(&g_default_namespace,
361 exe_path.c_str(), &exe_info.file_stat,
362 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700363 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700364 si->phdr = exe_info.phdr;
365 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700366 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
367 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
368 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700369 si->set_main_executable();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700370 init_link_map_head(*si, exe_path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700371
372 // Register the main executable and the linker upfront to have
373 // gdb aware of them before loading the rest of the dependency
374 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700375 //
376 // gdb expects the linker to be in the debug shared object list.
377 // Without this, gdb has trouble locating the linker's ".text"
378 // and ".plt" sections. Gdb could also potentially use this to
379 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
380 //
381 insert_link_map_into_debug_map(&si->link_map_head);
382 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700383
Ryan Prichard07440a82018-11-22 03:16:06 -0800384 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700385
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700386 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800387
388 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700389 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700390 // We don't use async_safe_fatal here because we don't want a tombstone:
391 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800392 // investigations because some app's trying to launch an executable that
393 // hasn't worked in at least three years, and we've "helpfully" dropped a
394 // tombstone for them. The tombstone never provided any detail relevant to
395 // fixing the problem anyway, and the utility of drawing extra attention
396 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700397 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700398 "\"%s\": error: Android 5.0 and later only support "
399 "position-independent executables (-fPIE).\n",
400 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700401 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700402 }
403
404 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
405 parse_LD_LIBRARY_PATH(ldpath_env);
406 parse_LD_PRELOAD(ldpreload_env);
407
Ryan Prichard8f639a42018-10-01 23:10:05 -0700408 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700409
Elliott Hughesad2d0382017-07-31 11:43:34 -0700410 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700411
412 // add somain to global group
413 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900414 // ... and add it to all other linked namespaces
415 for (auto linked_ns : namespaces) {
416 if (linked_ns != &g_default_namespace) {
417 linked_ns->add_soinfo(somain);
418 somain->add_secondary_namespace(linked_ns);
419 }
420 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700421
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800422 linker_setup_exe_static_tls(g_argv[0]);
423
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700424 // Load ld_preloads and dependencies.
425 std::vector<const char*> needed_library_name_list;
426 size_t ld_preloads_count = 0;
427
428 for (const auto& ld_preload_name : g_ld_preload_names) {
429 needed_library_name_list.push_back(ld_preload_name.c_str());
430 ++ld_preloads_count;
431 }
432
433 for_each_dt_needed(si, [&](const char* name) {
434 needed_library_name_list.push_back(name);
435 });
436
437 const char** needed_library_names = &needed_library_name_list[0];
438 size_t needed_libraries_count = needed_library_name_list.size();
439
440 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800441 !find_libraries(&g_default_namespace,
442 si,
443 needed_library_names,
444 needed_libraries_count,
445 nullptr,
446 &g_ld_preloads,
447 ld_preloads_count,
448 RTLD_GLOBAL,
449 nullptr,
450 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900451 true /* search_linked_namespaces */,
Jiyong Park02586a22017-05-20 01:01:24 +0900452 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700453 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700454 } else if (needed_libraries_count == 0) {
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400455 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700456 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700457 }
458 si->increment_ref_count();
459 }
460
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800461 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800462 __libc_init_main_thread_final();
463
Elliott Hughesad2d0382017-07-31 11:43:34 -0700464 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700465
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800466 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800467 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700468
469#if TIMING
470 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700471 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
472 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
473 static_cast<long long>(t1.tv_usec)) -
474 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
475 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700476#endif
477#if STATS
478 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", g_argv[0],
479 linker_stats.count[kRelocAbsolute],
480 linker_stats.count[kRelocRelative],
481 linker_stats.count[kRelocCopy],
482 linker_stats.count[kRelocSymbol]);
483#endif
484#if COUNT_PAGES
485 {
486 unsigned n;
487 unsigned i;
488 unsigned count = 0;
489 for (n = 0; n < 4096; n++) {
490 if (bitmask[n]) {
491 unsigned x = bitmask[n];
492#if defined(__LP64__)
493 for (i = 0; i < 32; i++) {
494#else
495 for (i = 0; i < 8; i++) {
496#endif
497 if (x & 1) {
498 count++;
499 }
500 x >>= 1;
501 }
502 }
503 }
504 PRINT("PAGES MODIFIED: %s: %d (%dKB)", g_argv[0], count, count * 4);
505 }
506#endif
507
508#if TIMING || STATS || COUNT_PAGES
509 fflush(stdout);
510#endif
511
Vic Yangbb7e1232019-01-29 20:23:16 -0800512 // We are about to hand control over to the executable loaded. We don't want
513 // to leave dirty pages behind unnecessarily.
514 purge_unused_memory();
515
Ryan Prichard8f639a42018-10-01 23:10:05 -0700516 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700517 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
518 return entry;
519}
520
521/* Compute the load-bias of an existing executable. This shall only
522 * be used to compute the load bias of an executable or shared library
523 * that was loaded by the kernel itself.
524 *
525 * Input:
526 * elf -> address of ELF header, assumed to be at the start of the file.
527 * Return:
528 * load bias, i.e. add the value of any p_vaddr in the file to get
529 * the corresponding address in memory.
530 */
531static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
532 ElfW(Addr) offset = elf->e_phoff;
533 const ElfW(Phdr)* phdr_table =
534 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
535 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
536
537 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
538 if (phdr->p_type == PT_LOAD) {
539 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
540 }
541 }
542 return 0;
543}
544
Ryan Prichard9729f352018-07-13 22:40:26 -0700545/* Find the load bias and base address of an executable or shared object loaded
546 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
547 *
548 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
549 */
550static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
551 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
552 for (size_t i = 0; i < phdr_count; ++i) {
553 if (phdr_table[i].p_type == PT_PHDR) {
554 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
555 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
556 return;
557 }
558 }
559 async_safe_fatal("Could not find a PHDR: broken executable?");
560}
561
Ryan Prichard1990ba52019-02-07 21:31:31 -0800562// Detect an attempt to run the linker on itself. e.g.:
563// /system/bin/linker64 /system/bin/linker64
564// Use priority-1 to run this constructor before other constructors.
565__attribute__((constructor(1))) static void detect_self_exec() {
566 // Normally, the linker initializes the auxv global before calling its
567 // constructors. If the linker loads itself, though, the first loader calls
568 // the second loader's constructors before calling __linker_init.
569 if (__libc_shared_globals()->auxv != nullptr) {
570 return;
571 }
572#if defined(__i386__)
573 // We don't have access to the auxv struct from here, so use the int 0x80
574 // fallback.
575 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
576#endif
577 __linker_error("error: linker cannot load itself\n");
578}
579
Ryan Prichard742982d2018-05-30 22:32:17 -0700580static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700581__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700582
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700583/*
584 * This is the entry point for the linker, called from begin.S. This
585 * method is responsible for fixing the linker's own relocations, and
586 * then calling __linker_init_post_relocation().
587 *
588 * Because this method is called before the linker has fixed it's own
589 * relocations, any attempt to reference an extern variable, extern
590 * function, or other GOT reference will generate a segfault.
591 */
592extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800593 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700594 KernelArgumentBlock args(raw_args);
Ryan Prichard45d13492019-01-03 02:51:30 -0800595 bionic_tcb temp_tcb = {};
596 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700597
Ryan Prichard8f639a42018-10-01 23:10:05 -0700598 // When the linker is run by itself (rather than as an interpreter for
599 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800600 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700601 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800602 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
603 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700604 ElfW(Addr) load_bias;
605 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800606 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700607 &linker_addr, &load_bias);
608 }
George Burgess IV70591002017-06-27 16:23:45 -0700609
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700610 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
611 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
612
Ryan Prichard04896452018-08-20 17:44:42 -0700613 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700614
Ryan Prichard04896452018-08-20 17:44:42 -0700615 tmp_linker_so.base = linker_addr;
616 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
617 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
618 tmp_linker_so.dynamic = nullptr;
619 tmp_linker_so.phdr = phdr;
620 tmp_linker_so.phnum = elf_hdr->e_phnum;
621 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700622
623 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700624 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700625
626 // This might not be obvious... The reasons why we pass g_empty_list
627 // in place of local_group here are (1) we do not really need it, because
628 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
629 // itself without having to look into local_group and (2) allocators
630 // are not yet initialized, and therefore we cannot use linked_list.push_*
631 // functions at this point.
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400632 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 -0700633
Ryan Prichard04896452018-08-20 17:44:42 -0700634 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700635}
636
637/*
638 * This code is called after the linker has linked itself and fixed its own
639 * GOT. It is safe to make references to externs and other non-local data at
640 * this point. The compiler sometimes moves GOT references earlier in a
641 * function, so avoid inlining this function (http://b/80503879).
642 */
643static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700644__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800645 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800646 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700647
648 // We didn't protect the linker's RELRO pages in link_image because we
649 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700650 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700651
652 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800653 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700654
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700655 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700656 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700657
Ryan Prichard8f639a42018-10-01 23:10:05 -0700658 // When the linker is run directly rather than acting as PT_INTERP, parse
659 // arguments and determine the executable to load. When it's instead acting
660 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
661 // linker's _start.
662 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800663 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700664 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
665 // We're being asked to behave like ldd(1).
666 g_is_ldd = true;
667 exe_to_load = args.argv[2];
668 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700669 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700670 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
671 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700672 "\n"
673 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
674 "this program because it's the PT_INTERP of a dynamic executable.\n"
675 "\n"
676 "This program can also be run directly to load and run a dynamic executable. The\n"
677 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700678 "page-aligned offset.\n"
679 "\n"
680 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700681 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700682 _exit(EXIT_SUCCESS);
683 } else {
684 exe_to_load = args.argv[1];
685 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700686 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700687 }
688
Ryan Prichard8f639a42018-10-01 23:10:05 -0700689 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800690 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
691 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700692 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800693 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700694
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700695 // Initialize static variables. Note that in order to
696 // get correct libdl_info we need to call constructors
697 // before get_libdl_info().
Ryan Prichard04896452018-08-20 17:44:42 -0700698 sonext = solist = solinker = get_libdl_info(kLinkerPath, tmp_linker_so);
699 g_default_namespace.add_soinfo(solinker);
700 init_link_map_head(*solinker, kLinkerPath);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700701
Ryan Prichard8f639a42018-10-01 23:10:05 -0700702 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700703
Elliott Hughes90f96b92019-05-09 15:56:39 -0700704 if (g_is_ldd) _exit(EXIT_SUCCESS);
705
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700706 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
707
708 // Return the address that the calling assembly stub should jump to.
709 return start_address;
710}