blob: 13edfe1f7cea5ea8d097b190c43a66e9cefec686 [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"
32#include "linker_gdb_support.h"
33#include "linker_globals.h"
34#include "linker_phdr.h"
35#include "linker_utils.h"
36
37#include "private/bionic_globals.h"
38#include "private/bionic_tls.h"
39#include "private/KernelArgumentBlock.h"
40
41#include "android-base/strings.h"
42#include "android-base/stringprintf.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080043#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -070044#include "debuggerd/client.h"
Dan Willemsen7ec52b12016-11-28 17:02:25 -080045#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -070046
47#include <vector>
48
49extern void __libc_init_globals(KernelArgumentBlock&);
50extern void __libc_init_AT_SECURE(KernelArgumentBlock&);
51
52extern "C" void _start();
53
54static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
55
56// These should be preserved static to avoid emitting
57// RELATIVE relocations for the part of the code running
58// before linker links itself.
59
60// TODO (dimtiry): remove somain, rename solist to solist_head
61static soinfo* solist;
62static soinfo* sonext;
63static soinfo* somain; // main process, always the one after libdl_info
64
65void solist_add_soinfo(soinfo* si) {
66 sonext->next = si;
67 sonext = si;
68}
69
70bool solist_remove_soinfo(soinfo* si) {
71 soinfo *prev = nullptr, *trav;
72 for (trav = solist; trav != nullptr; trav = trav->next) {
73 if (trav == si) {
74 break;
75 }
76 prev = trav;
77 }
78
79 if (trav == nullptr) {
80 // si was not in solist
81 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
82 return false;
83 }
84
85 // prev will never be null, because the first entry in solist is
86 // always the static libdl_info.
87 prev->next = si->next;
88 if (si == sonext) {
89 sonext = prev;
90 }
91
92 return true;
93}
94
95soinfo* solist_get_head() {
96 return solist;
97}
98
99soinfo* solist_get_somain() {
100 return somain;
101}
102
103int g_ld_debug_verbosity;
104abort_msg_t* g_abort_message = nullptr; // For debuggerd.
105
106static std::vector<std::string> g_ld_preload_names;
107
108static std::vector<soinfo*> g_ld_preloads;
109
110static void parse_path(const char* path, const char* delimiters,
111 std::vector<std::string>* resolved_paths) {
112 std::vector<std::string> paths;
113 split_path(path, delimiters, &paths);
114 resolve_paths(paths, resolved_paths);
115}
116
117static void parse_LD_LIBRARY_PATH(const char* path) {
118 std::vector<std::string> ld_libary_paths;
119 parse_path(path, ":", &ld_libary_paths);
120 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
121}
122
123static void parse_LD_PRELOAD(const char* path) {
124 g_ld_preload_names.clear();
125 if (path != nullptr) {
126 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
127 g_ld_preload_names = android::base::Split(path, " :");
128 std::remove_if(g_ld_preload_names.begin(),
129 g_ld_preload_names.end(),
130 [] (const std::string& s) { return s.empty(); });
131 }
132}
133
134// An empty list of soinfos
135static soinfo_list_t g_empty_list;
136
137static void add_vdso(KernelArgumentBlock& args __unused) {
138#if defined(AT_SYSINFO_EHDR)
139 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
140 if (ehdr_vdso == nullptr) {
141 return;
142 }
143
144 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
145
146 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
147 si->phnum = ehdr_vdso->e_phnum;
148 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
149 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
150 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
151
152 si->prelink_image();
153 si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr);
154#endif
155}
156
157/* gdb expects the linker to be in the debug shared object list.
158 * Without this, gdb has trouble locating the linker's ".text"
159 * and ".plt" sections. Gdb could also potentially use this to
160 * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
161 * Note that the linker shouldn't be on the soinfo list.
162 */
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800163static void init_linker_info_for_gdb(ElfW(Addr) linker_base, char* linker_path) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700164 static link_map linker_link_map_for_gdb;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700165
166 linker_link_map_for_gdb.l_addr = linker_base;
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800167 linker_link_map_for_gdb.l_name = linker_path;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700168
169 /*
170 * Set the dynamic field in the link map otherwise gdb will complain with
171 * the following:
172 * warning: .dynamic section for "/system/bin/linker" is not at the
173 * expected address (wrong library or version mismatch?)
174 */
175 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
176 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
177 phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
178 &linker_link_map_for_gdb.l_ld, nullptr);
179
180 insert_link_map_into_debug_map(&linker_link_map_for_gdb);
181}
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()) {
188 char path[PATH_MAX];
189 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
190 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
191 __libc_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
192 }
193 executable_path = std::string(path, path_len);
194 }
195
196 return executable_path.c_str();
197}
198
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800199#if defined(__LP64__)
200static char kLinkerPath[] = "/system/bin/linker64";
201#else
202static char kLinkerPath[] = "/system/bin/linker";
203#endif
204
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700205/*
206 * This code is called after the linker has linked itself and
207 * fixed it's own GOT. It is safe to make references to externs
208 * and other non-local data at this point.
209 */
210static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) {
211#if TIMING
212 struct timeval t0, t1;
213 gettimeofday(&t0, 0);
214#endif
215
216 // Sanitize the environment.
217 __libc_init_AT_SECURE(args);
218
219 // Initialize system properties
220 __system_properties_init(); // may use 'environ'
221
222 // Register the debuggerd signal handler.
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800223#ifdef __ANDROID__
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700224 debuggerd_callbacks_t callbacks = {
225 .get_abort_message = []() {
226 return g_abort_message;
227 },
228 .post_dump = &notify_gdb_of_libraries,
229 };
230 debuggerd_init(&callbacks);
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800231#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700232
233 g_linker_logger.ResetState();
234
235 // Get a few environment variables.
236 const char* LD_DEBUG = getenv("LD_DEBUG");
237 if (LD_DEBUG != nullptr) {
238 g_ld_debug_verbosity = atoi(LD_DEBUG);
239 }
240
241#if defined(__LP64__)
242 INFO("[ Android dynamic linker (64-bit) ]");
243#else
244 INFO("[ Android dynamic linker (32-bit) ]");
245#endif
246
247 // These should have been sanitized by __libc_init_AT_SECURE, but the test
248 // doesn't cost us anything.
249 const char* ldpath_env = nullptr;
250 const char* ldpreload_env = nullptr;
251 if (!getauxval(AT_SECURE)) {
252 ldpath_env = getenv("LD_LIBRARY_PATH");
253 if (ldpath_env != nullptr) {
254 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
255 }
256 ldpreload_env = getenv("LD_PRELOAD");
257 if (ldpreload_env != nullptr) {
258 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
259 }
260 }
261
262 struct stat file_stat;
263 // Stat "/proc/self/exe" instead of executable_path because
264 // the executable could be unlinked by this point and it should
265 // not cause a crash (see http://b/31084669)
266 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &file_stat)) != 0) {
267 __libc_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
268 }
269
270 const char* executable_path = get_executable_path();
271 soinfo* si = soinfo_alloc(&g_default_namespace, executable_path, &file_stat, 0, RTLD_GLOBAL);
272 if (si == nullptr) {
273 __libc_fatal("Couldn't allocate soinfo: out of memory?");
274 }
275
276 /* bootstrap the link map, the main exe always needs to be first */
277 si->set_main_executable();
278 link_map* map = &(si->link_map_head);
279
280 // Register the main executable and the linker upfront to have
281 // gdb aware of them before loading the rest of the dependency
282 // tree.
283 map->l_addr = 0;
284 map->l_name = const_cast<char*>(executable_path);
285 insert_link_map_into_debug_map(map);
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800286 init_linker_info_for_gdb(linker_base, kLinkerPath);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700287
288 // Extract information passed from the kernel.
289 si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
290 si->phnum = args.getauxval(AT_PHNUM);
291
292 /* Compute the value of si->base. We can't rely on the fact that
293 * the first entry is the PHDR because this will not be true
294 * for certain executables (e.g. some in the NDK unit test suite)
295 */
296 si->base = 0;
297 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
298 si->load_bias = 0;
299 for (size_t i = 0; i < si->phnum; ++i) {
300 if (si->phdr[i].p_type == PT_PHDR) {
301 si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
302 si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
303 break;
304 }
305 }
306 si->dynamic = nullptr;
307
308 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
309 if (elf_hdr->e_type != ET_DYN) {
310 __libc_fatal("\"%s\": error: only position independent executables (PIE) are supported.",
311 g_argv[0]);
312 }
313
314 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
315 parse_LD_LIBRARY_PATH(ldpath_env);
316 parse_LD_PRELOAD(ldpreload_env);
317
318 somain = si;
319
320 init_default_namespace();
321
322 if (!si->prelink_image()) {
323 __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", g_argv[0], linker_get_error_buffer());
324 }
325
326 // add somain to global group
327 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
328
329 // Load ld_preloads and dependencies.
330 std::vector<const char*> needed_library_name_list;
331 size_t ld_preloads_count = 0;
332
333 for (const auto& ld_preload_name : g_ld_preload_names) {
334 needed_library_name_list.push_back(ld_preload_name.c_str());
335 ++ld_preloads_count;
336 }
337
338 for_each_dt_needed(si, [&](const char* name) {
339 needed_library_name_list.push_back(name);
340 });
341
342 const char** needed_library_names = &needed_library_name_list[0];
343 size_t needed_libraries_count = needed_library_name_list.size();
344
345 if (needed_libraries_count > 0 &&
346 !find_libraries(&g_default_namespace, si, needed_library_names, needed_libraries_count,
347 nullptr, &g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr,
348 /* add_as_children */ true)) {
349 __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", g_argv[0], linker_get_error_buffer());
350 } else if (needed_libraries_count == 0) {
351 if (!si->link_image(g_empty_list, soinfo_list_t::make_list(si), nullptr)) {
352 __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", g_argv[0], linker_get_error_buffer());
353 }
354 si->increment_ref_count();
355 }
356
357 add_vdso(args);
358
359 {
360 ProtectedDataGuard guard;
361
362 si->call_pre_init_constructors();
363
364 /* After the prelink_image, the si->load_bias is initialized.
365 * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
366 * We need to update this value for so exe here. So Unwind_Backtrace
367 * for some arch like x86 could work correctly within so exe.
368 */
369 map->l_addr = si->load_bias;
370 si->call_constructors();
371 }
372
373#if TIMING
374 gettimeofday(&t1, nullptr);
375 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0], (int) (
376 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
377 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
378#endif
379#if STATS
380 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", g_argv[0],
381 linker_stats.count[kRelocAbsolute],
382 linker_stats.count[kRelocRelative],
383 linker_stats.count[kRelocCopy],
384 linker_stats.count[kRelocSymbol]);
385#endif
386#if COUNT_PAGES
387 {
388 unsigned n;
389 unsigned i;
390 unsigned count = 0;
391 for (n = 0; n < 4096; n++) {
392 if (bitmask[n]) {
393 unsigned x = bitmask[n];
394#if defined(__LP64__)
395 for (i = 0; i < 32; i++) {
396#else
397 for (i = 0; i < 8; i++) {
398#endif
399 if (x & 1) {
400 count++;
401 }
402 x >>= 1;
403 }
404 }
405 }
406 PRINT("PAGES MODIFIED: %s: %d (%dKB)", g_argv[0], count, count * 4);
407 }
408#endif
409
410#if TIMING || STATS || COUNT_PAGES
411 fflush(stdout);
412#endif
413
414 ElfW(Addr) entry = args.getauxval(AT_ENTRY);
415 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
416 return entry;
417}
418
419/* Compute the load-bias of an existing executable. This shall only
420 * be used to compute the load bias of an executable or shared library
421 * that was loaded by the kernel itself.
422 *
423 * Input:
424 * elf -> address of ELF header, assumed to be at the start of the file.
425 * Return:
426 * load bias, i.e. add the value of any p_vaddr in the file to get
427 * the corresponding address in memory.
428 */
429static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
430 ElfW(Addr) offset = elf->e_phoff;
431 const ElfW(Phdr)* phdr_table =
432 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
433 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
434
435 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
436 if (phdr->p_type == PT_LOAD) {
437 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
438 }
439 }
440 return 0;
441}
442
443static void __linker_cannot_link(const char* argv0) {
444 __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", argv0, linker_get_error_buffer());
445}
446
447/*
448 * This is the entry point for the linker, called from begin.S. This
449 * method is responsible for fixing the linker's own relocations, and
450 * then calling __linker_init_post_relocation().
451 *
452 * Because this method is called before the linker has fixed it's own
453 * relocations, any attempt to reference an extern variable, extern
454 * function, or other GOT reference will generate a segfault.
455 */
456extern "C" ElfW(Addr) __linker_init(void* raw_args) {
457 KernelArgumentBlock args(raw_args);
458
459 ElfW(Addr) linker_addr = args.getauxval(AT_BASE);
460 ElfW(Addr) entry_point = args.getauxval(AT_ENTRY);
461 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
462 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
463
464 soinfo linker_so(nullptr, nullptr, nullptr, 0, 0);
465
466 // If the linker is not acting as PT_INTERP entry_point is equal to
467 // _start. Which means that the linker is running as an executable and
468 // already linked by PT_INTERP.
469 //
470 // This happens when user tries to run 'adb shell /system/bin/linker'
471 // see also https://code.google.com/p/android/issues/detail?id=63174
472 if (reinterpret_cast<ElfW(Addr)>(&_start) == entry_point) {
473 __libc_format_fd(STDOUT_FILENO,
474 "This is %s, the helper program for shared library executables.\n",
475 args.argv[0]);
476 exit(0);
477 }
478
479 linker_so.base = linker_addr;
480 linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
481 linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
482 linker_so.dynamic = nullptr;
483 linker_so.phdr = phdr;
484 linker_so.phnum = elf_hdr->e_phnum;
485 linker_so.set_linker_flag();
486
487 // Prelink the linker so we can access linker globals.
488 if (!linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
489
490 // This might not be obvious... The reasons why we pass g_empty_list
491 // in place of local_group here are (1) we do not really need it, because
492 // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
493 // itself without having to look into local_group and (2) allocators
494 // are not yet initialized, and therefore we cannot use linked_list.push_*
495 // functions at this point.
496 if (!linker_so.link_image(g_empty_list, g_empty_list, nullptr)) __linker_cannot_link(args.argv[0]);
497
498#if defined(__i386__)
499 // On x86, we can't make system calls before this point.
500 // We can't move this up because this needs to assign to a global.
501 // Note that until we call __libc_init_main_thread below we have
502 // no TLS, so you shouldn't make a system call that can fail, because
503 // it will SEGV when it tries to set errno.
504 __libc_init_sysinfo(args);
505#endif
506
507 // Initialize the main thread (including TLS, so system calls really work).
508 __libc_init_main_thread(args);
509
510 // We didn't protect the linker's RELRO pages in link_image because we
511 // couldn't make system calls on x86 at that point, but we can now...
512 if (!linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
513
514 // Initialize the linker's static libc's globals
515 __libc_init_globals(args);
516
517 // store argc/argv/envp to use them for calling constructors
518 g_argc = args.argc;
519 g_argv = args.argv;
520 g_envp = args.envp;
521
522 // Initialize the linker's own global variables
523 linker_so.call_constructors();
524
525 // Initialize static variables. Note that in order to
526 // get correct libdl_info we need to call constructors
527 // before get_libdl_info().
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800528 sonext = solist = get_libdl_info(kLinkerPath);
529 g_default_namespace.add_soinfo(solist);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700530
531 // We have successfully fixed our own relocations. It's safe to run
532 // the main part of the linker now.
533 args.abort_message_ptr = &g_abort_message;
534 ElfW(Addr) start_address = __linker_init_post_relocation(args, linker_addr);
535
536 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
537
538 // Return the address that the calling assembly stub should jump to.
539 return start_address;
540}