blob: c5e0b9635acb3e64800dd6b1f4a0ee4e0aa7521a [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
31#include "linker_debug.h"
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -070032#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070033#include "linker_gdb_support.h"
34#include "linker_globals.h"
35#include "linker_phdr.h"
36#include "linker_utils.h"
37
38#include "private/bionic_globals.h"
39#include "private/bionic_tls.h"
40#include "private/KernelArgumentBlock.h"
41
42#include "android-base/strings.h"
43#include "android-base/stringprintf.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080044#ifdef __ANDROID__
Josh Gao2a3b4fa2016-10-26 17:55:49 -070045#include "debuggerd/handler.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080046#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -070047
Christopher Ferris7a3681e2017-04-24 17:48:32 -070048#include <async_safe/log.h>
49
Dimitry Ivanov3f660572016-09-09 10:00:39 -070050#include <vector>
51
52extern void __libc_init_globals(KernelArgumentBlock&);
53extern void __libc_init_AT_SECURE(KernelArgumentBlock&);
54
55extern "C" void _start();
56
57static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
58
Ryan Prichard9729f352018-07-13 22:40:26 -070059static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
60 ElfW(Addr)* base, ElfW(Addr)* load_bias);
61
Dimitry Ivanov3f660572016-09-09 10:00:39 -070062// These should be preserved static to avoid emitting
63// RELATIVE relocations for the part of the code running
64// before linker links itself.
65
66// TODO (dimtiry): remove somain, rename solist to solist_head
67static soinfo* solist;
68static soinfo* sonext;
69static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070070static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020071static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070072
73void solist_add_soinfo(soinfo* si) {
74 sonext->next = si;
75 sonext = si;
76}
77
78bool solist_remove_soinfo(soinfo* si) {
79 soinfo *prev = nullptr, *trav;
80 for (trav = solist; trav != nullptr; trav = trav->next) {
81 if (trav == si) {
82 break;
83 }
84 prev = trav;
85 }
86
87 if (trav == nullptr) {
88 // si was not in solist
89 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
90 return false;
91 }
92
93 // prev will never be null, because the first entry in solist is
94 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -070095 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -070096 prev->next = si->next;
97 if (si == sonext) {
98 sonext = prev;
99 }
100
101 return true;
102}
103
104soinfo* solist_get_head() {
105 return solist;
106}
107
108soinfo* solist_get_somain() {
109 return somain;
110}
111
dimitry8b142562018-05-09 15:22:38 +0200112soinfo* solist_get_vdso() {
113 return vdso;
114}
115
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700116int g_ld_debug_verbosity;
117abort_msg_t* g_abort_message = nullptr; // For debuggerd.
118
119static std::vector<std::string> g_ld_preload_names;
120
121static std::vector<soinfo*> g_ld_preloads;
122
123static void parse_path(const char* path, const char* delimiters,
124 std::vector<std::string>* resolved_paths) {
125 std::vector<std::string> paths;
126 split_path(path, delimiters, &paths);
127 resolve_paths(paths, resolved_paths);
128}
129
130static void parse_LD_LIBRARY_PATH(const char* path) {
131 std::vector<std::string> ld_libary_paths;
132 parse_path(path, ":", &ld_libary_paths);
133 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
134}
135
136static void parse_LD_PRELOAD(const char* path) {
137 g_ld_preload_names.clear();
138 if (path != nullptr) {
139 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
140 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700141 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 -0700142 [](const std::string& s) { return s.empty(); }),
143 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700144 }
145}
146
147// An empty list of soinfos
148static soinfo_list_t g_empty_list;
149
dimitryf9abbf62017-07-06 12:17:14 +0200150static void add_vdso(KernelArgumentBlock& args) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700151 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
152 if (ehdr_vdso == nullptr) {
153 return;
154 }
155
156 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
157
158 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
159 si->phnum = ehdr_vdso->e_phnum;
160 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
161 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
162 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
163
164 si->prelink_image();
165 si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200166 // prevents accidental unloads...
167 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
168 si->set_linked();
169 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200170
171 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700172}
173
Ryan Prichard04896452018-08-20 17:44:42 -0700174// Initializes an soinfo's link_map_head field using other fields from the
175// soinfo (phdr, phnum, load_bias).
176static void init_link_map_head(soinfo& info, const char* linker_path) {
177 auto& map = info.link_map_head;
178 map.l_addr = info.load_bias;
179 map.l_name = const_cast<char*>(linker_path);
180 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700181}
182
183extern "C" int __system_properties_init(void);
184
185static const char* get_executable_path() {
186 static std::string executable_path;
187 if (executable_path.empty()) {
Jiyong Park31cd08f2018-06-01 19:18:56 +0900188 if (!is_init()) {
189 char path[PATH_MAX];
190 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
191 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
192 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
193 }
194 executable_path = std::string(path, path_len);
195 } else {
196 executable_path = "/init";
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700197 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700198 }
199
200 return executable_path.c_str();
201}
202
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800203#if defined(__LP64__)
204static char kLinkerPath[] = "/system/bin/linker64";
205#else
206static char kLinkerPath[] = "/system/bin/linker";
207#endif
208
Elliott Hughesad2d0382017-07-31 11:43:34 -0700209static void __linker_cannot_link(const char* argv0) {
dimitry04f7a792017-09-29 11:52:17 +0200210 async_safe_format_fd(STDERR_FILENO,
211 "CANNOT LINK EXECUTABLE \"%s\": %s\n",
212 argv0,
213 linker_get_error_buffer());
214
215 async_safe_format_log(ANDROID_LOG_FATAL,
216 "linker",
217 "CANNOT LINK EXECUTABLE \"%s\": %s",
218 argv0,
219 linker_get_error_buffer());
220 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700221}
222
Ryan Prichard742982d2018-05-30 22:32:17 -0700223static ElfW(Addr) linker_main(KernelArgumentBlock& args) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800224 ProtectedDataGuard guard;
225
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700226#if TIMING
227 struct timeval t0, t1;
228 gettimeofday(&t0, 0);
229#endif
230
231 // Sanitize the environment.
232 __libc_init_AT_SECURE(args);
233
234 // Initialize system properties
235 __system_properties_init(); // may use 'environ'
236
237 // Register the debuggerd signal handler.
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800238#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700239 debuggerd_callbacks_t callbacks = {
240 .get_abort_message = []() {
241 return g_abort_message;
242 },
243 .post_dump = &notify_gdb_of_libraries,
244 };
245 debuggerd_init(&callbacks);
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800246#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700247
248 g_linker_logger.ResetState();
249
250 // Get a few environment variables.
251 const char* LD_DEBUG = getenv("LD_DEBUG");
252 if (LD_DEBUG != nullptr) {
253 g_ld_debug_verbosity = atoi(LD_DEBUG);
254 }
255
256#if defined(__LP64__)
257 INFO("[ Android dynamic linker (64-bit) ]");
258#else
259 INFO("[ Android dynamic linker (32-bit) ]");
260#endif
261
262 // These should have been sanitized by __libc_init_AT_SECURE, but the test
263 // doesn't cost us anything.
264 const char* ldpath_env = nullptr;
265 const char* ldpreload_env = nullptr;
266 if (!getauxval(AT_SECURE)) {
267 ldpath_env = getenv("LD_LIBRARY_PATH");
268 if (ldpath_env != nullptr) {
269 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
270 }
271 ldpreload_env = getenv("LD_PRELOAD");
272 if (ldpreload_env != nullptr) {
273 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
274 }
275 }
276
277 struct stat file_stat;
278 // Stat "/proc/self/exe" instead of executable_path because
279 // the executable could be unlinked by this point and it should
280 // not cause a crash (see http://b/31084669)
Jiyong Park31cd08f2018-06-01 19:18:56 +0900281 if (!is_init()) {
282 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &file_stat)) != 0) {
283 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
284 }
285 } else {
286 // /proc fs is not mounted when init starts. Therefore we can't use
287 // /proc/self/exe for init.
288 stat("/init", &file_stat);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700289 }
290
Ryan Prichard04896452018-08-20 17:44:42 -0700291 // Initialize the main exe's soinfo.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700292 const char* executable_path = get_executable_path();
293 soinfo* si = soinfo_alloc(&g_default_namespace, executable_path, &file_stat, 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700294 somain = si;
295 si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
296 si->phnum = args.getauxval(AT_PHNUM);
297 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
298 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
299 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700300 si->set_main_executable();
Ryan Prichard04896452018-08-20 17:44:42 -0700301 init_link_map_head(*si, executable_path);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700302
303 // Register the main executable and the linker upfront to have
304 // gdb aware of them before loading the rest of the dependency
305 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700306 //
307 // gdb expects the linker to be in the debug shared object list.
308 // Without this, gdb has trouble locating the linker's ".text"
309 // and ".plt" sections. Gdb could also potentially use this to
310 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
311 //
312 insert_link_map_into_debug_map(&si->link_map_head);
313 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700314
Ryan Prichard14dd9922018-08-20 17:43:44 -0700315 add_vdso(args);
316
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700317 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800318
319 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700320 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700321 // We don't use async_safe_fatal here because we don't want a tombstone:
322 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800323 // investigations because some app's trying to launch an executable that
324 // hasn't worked in at least three years, and we've "helpfully" dropped a
325 // tombstone for them. The tombstone never provided any detail relevant to
326 // fixing the problem anyway, and the utility of drawing extra attention
327 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700328 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700329 "\"%s\": error: Android 5.0 and later only support "
330 "position-independent executables (-fPIE).\n",
331 g_argv[0]);
Dan Albert95e2e6f2017-01-31 16:02:43 -0800332 exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700333 }
334
335 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
336 parse_LD_LIBRARY_PATH(ldpath_env);
337 parse_LD_PRELOAD(ldpreload_env);
338
Jiyong Park02586a22017-05-20 01:01:24 +0900339 std::vector<android_namespace_t*> namespaces = init_default_namespaces(executable_path);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700340
Elliott Hughesad2d0382017-07-31 11:43:34 -0700341 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700342
343 // add somain to global group
344 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900345 // ... and add it to all other linked namespaces
346 for (auto linked_ns : namespaces) {
347 if (linked_ns != &g_default_namespace) {
348 linked_ns->add_soinfo(somain);
349 somain->add_secondary_namespace(linked_ns);
350 }
351 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700352
353 // Load ld_preloads and dependencies.
354 std::vector<const char*> needed_library_name_list;
355 size_t ld_preloads_count = 0;
356
357 for (const auto& ld_preload_name : g_ld_preload_names) {
358 needed_library_name_list.push_back(ld_preload_name.c_str());
359 ++ld_preloads_count;
360 }
361
362 for_each_dt_needed(si, [&](const char* name) {
363 needed_library_name_list.push_back(name);
364 });
365
366 const char** needed_library_names = &needed_library_name_list[0];
367 size_t needed_libraries_count = needed_library_name_list.size();
368
369 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800370 !find_libraries(&g_default_namespace,
371 si,
372 needed_library_names,
373 needed_libraries_count,
374 nullptr,
375 &g_ld_preloads,
376 ld_preloads_count,
377 RTLD_GLOBAL,
378 nullptr,
379 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900380 true /* search_linked_namespaces */,
Jiyong Park02586a22017-05-20 01:01:24 +0900381 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700382 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700383 } else if (needed_libraries_count == 0) {
384 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700385 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700386 }
387 si->increment_ref_count();
388 }
389
Elliott Hughesad2d0382017-07-31 11:43:34 -0700390 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700391
Ryan Prichard6631f9b2018-04-30 18:29:32 -0700392 // Store a pointer to the kernel argument block in a TLS slot to be
393 // picked up by the libc constructor.
394 __get_tls()[TLS_SLOT_BIONIC_PREINIT] = &args;
395
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800396 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800397 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700398
399#if TIMING
400 gettimeofday(&t1, nullptr);
401 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0], (int) (
402 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
403 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
404#endif
405#if STATS
406 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", g_argv[0],
407 linker_stats.count[kRelocAbsolute],
408 linker_stats.count[kRelocRelative],
409 linker_stats.count[kRelocCopy],
410 linker_stats.count[kRelocSymbol]);
411#endif
412#if COUNT_PAGES
413 {
414 unsigned n;
415 unsigned i;
416 unsigned count = 0;
417 for (n = 0; n < 4096; n++) {
418 if (bitmask[n]) {
419 unsigned x = bitmask[n];
420#if defined(__LP64__)
421 for (i = 0; i < 32; i++) {
422#else
423 for (i = 0; i < 8; i++) {
424#endif
425 if (x & 1) {
426 count++;
427 }
428 x >>= 1;
429 }
430 }
431 }
432 PRINT("PAGES MODIFIED: %s: %d (%dKB)", g_argv[0], count, count * 4);
433 }
434#endif
435
436#if TIMING || STATS || COUNT_PAGES
437 fflush(stdout);
438#endif
439
440 ElfW(Addr) entry = args.getauxval(AT_ENTRY);
441 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
442 return entry;
443}
444
445/* Compute the load-bias of an existing executable. This shall only
446 * be used to compute the load bias of an executable or shared library
447 * that was loaded by the kernel itself.
448 *
449 * Input:
450 * elf -> address of ELF header, assumed to be at the start of the file.
451 * Return:
452 * load bias, i.e. add the value of any p_vaddr in the file to get
453 * the corresponding address in memory.
454 */
455static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
456 ElfW(Addr) offset = elf->e_phoff;
457 const ElfW(Phdr)* phdr_table =
458 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
459 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
460
461 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
462 if (phdr->p_type == PT_LOAD) {
463 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
464 }
465 }
466 return 0;
467}
468
Ryan Prichard9729f352018-07-13 22:40:26 -0700469/* Find the load bias and base address of an executable or shared object loaded
470 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
471 *
472 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
473 */
474static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
475 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
476 for (size_t i = 0; i < phdr_count; ++i) {
477 if (phdr_table[i].p_type == PT_PHDR) {
478 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
479 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
480 return;
481 }
482 }
483 async_safe_fatal("Could not find a PHDR: broken executable?");
484}
485
Ryan Prichard742982d2018-05-30 22:32:17 -0700486static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700487__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700488
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700489/*
490 * This is the entry point for the linker, called from begin.S. This
491 * method is responsible for fixing the linker's own relocations, and
492 * then calling __linker_init_post_relocation().
493 *
494 * Because this method is called before the linker has fixed it's own
495 * relocations, any attempt to reference an extern variable, extern
496 * function, or other GOT reference will generate a segfault.
497 */
498extern "C" ElfW(Addr) __linker_init(void* raw_args) {
499 KernelArgumentBlock args(raw_args);
500
Ryan Prichard27475b52018-05-17 17:14:18 -0700501#if defined(__i386__)
502 __libc_init_sysinfo(args);
503#endif
504
Ryan Prichard9729f352018-07-13 22:40:26 -0700505 ElfW(Addr) linker_addr = args.getauxval(AT_BASE);
506 if (linker_addr == 0) {
507 // When the linker is run by itself (rather than as an interpreter for
508 // another program), AT_BASE is 0. In that case, the AT_PHDR and AT_PHNUM
509 // aux values describe the linker, so use the phdr to find the linker's
510 // base address.
511 ElfW(Addr) load_bias;
512 get_elf_base_from_phdr(
513 reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR)), args.getauxval(AT_PHNUM),
514 &linker_addr, &load_bias);
515 }
George Burgess IV70591002017-06-27 16:23:45 -0700516
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700517 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
518 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
519
Ryan Prichard04896452018-08-20 17:44:42 -0700520 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700521
Ryan Prichard04896452018-08-20 17:44:42 -0700522 tmp_linker_so.base = linker_addr;
523 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
524 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
525 tmp_linker_so.dynamic = nullptr;
526 tmp_linker_so.phdr = phdr;
527 tmp_linker_so.phnum = elf_hdr->e_phnum;
528 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700529
530 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700531 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700532
533 // This might not be obvious... The reasons why we pass g_empty_list
534 // in place of local_group here are (1) we do not really need it, because
535 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
536 // itself without having to look into local_group and (2) allocators
537 // are not yet initialized, and therefore we cannot use linked_list.push_*
538 // functions at this point.
Ryan Prichard04896452018-08-20 17:44:42 -0700539 if (!tmp_linker_so.link_image(g_empty_list, g_empty_list, nullptr)) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700540
Ryan Prichard04896452018-08-20 17:44:42 -0700541 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700542}
543
544/*
545 * This code is called after the linker has linked itself and fixed its own
546 * GOT. It is safe to make references to externs and other non-local data at
547 * this point. The compiler sometimes moves GOT references earlier in a
548 * function, so avoid inlining this function (http://b/80503879).
549 */
550static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700551__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700552 // Initialize the main thread (including TLS, so system calls really work).
553 __libc_init_main_thread(args);
554
555 // We didn't protect the linker's RELRO pages in link_image because we
556 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700557 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700558
Josh Gaof6e5b582018-06-01 15:30:54 -0700559 // Initialize the linker/libc.so shared global inside the linker.
560 static libc_shared_globals shared_globals;
561 __libc_shared_globals = &shared_globals;
562 __libc_init_shared_globals(&shared_globals);
563 args.shared_globals = __libc_shared_globals;
564
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700565 // Initialize the linker's static libc's globals
566 __libc_init_globals(args);
567
568 // store argc/argv/envp to use them for calling constructors
569 g_argc = args.argc;
570 g_argv = args.argv;
571 g_envp = args.envp;
572
573 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700574 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700575
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700576 // If the linker is not acting as PT_INTERP entry_point is equal to
577 // _start. Which means that the linker is running as an executable and
578 // already linked by PT_INTERP.
579 //
580 // This happens when user tries to run 'adb shell /system/bin/linker'
581 // see also https://code.google.com/p/android/issues/detail?id=63174
Ryan Prichard742982d2018-05-30 22:32:17 -0700582 ElfW(Addr) entry_point = args.getauxval(AT_ENTRY);
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700583 if (reinterpret_cast<ElfW(Addr)>(&_start) == entry_point) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700584 async_safe_format_fd(STDOUT_FILENO,
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700585 "This is %s, the helper program for dynamic executables.\n",
586 args.argv[0]);
587 exit(0);
588 }
589
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700590 // Initialize static variables. Note that in order to
591 // get correct libdl_info we need to call constructors
592 // before get_libdl_info().
Ryan Prichard04896452018-08-20 17:44:42 -0700593 sonext = solist = solinker = get_libdl_info(kLinkerPath, tmp_linker_so);
594 g_default_namespace.add_soinfo(solinker);
595 init_link_map_head(*solinker, kLinkerPath);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700596
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700597 args.abort_message_ptr = &g_abort_message;
Ryan Prichard742982d2018-05-30 22:32:17 -0700598 ElfW(Addr) start_address = linker_main(args);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700599
600 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
601
602 // Return the address that the calling assembly stub should jump to.
603 return start_address;
604}