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