1 /*
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 <link.h>
32 #include <sys/auxv.h>
33
34 #include "linker_debug.h"
35 #include "linker_debuggerd.h"
36 #include "linker_cfi.h"
37 #include "linker_gdb_support.h"
38 #include "linker_globals.h"
39 #include "linker_phdr.h"
40 #include "linker_relocate.h"
41 #include "linker_tls.h"
42 #include "linker_utils.h"
43
44 #include "private/bionic_auxv.h"
45 #include "private/bionic_call_ifunc_resolver.h"
46 #include "private/bionic_globals.h"
47 #include "private/bionic_tls.h"
48 #include "private/KernelArgumentBlock.h"
49
50 #include "android-base/unique_fd.h"
51 #include "android-base/strings.h"
52 #include "android-base/stringprintf.h"
53
54 #include <async_safe/log.h>
55 #include <bionic/libc_init_common.h>
56 #include <bionic/pthread_internal.h>
57
58 #include <vector>
59
60 __LIBC_HIDDEN__ extern "C" void _start();
61
62 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
63
64 static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
65 ElfW(Addr)* base, ElfW(Addr)* load_bias);
66
67 static void set_bss_vma_name(soinfo* si);
68
69 // These should be preserved static to avoid emitting
70 // RELATIVE relocations for the part of the code running
71 // before linker links itself.
72
73 // TODO (dimtiry): remove somain, rename solist to solist_head
74 static soinfo* solist;
75 static soinfo* sonext;
76 static soinfo* somain; // main process, always the one after libdl_info
77 static soinfo* solinker;
78 static soinfo* vdso; // vdso if present
79
solist_add_soinfo(soinfo * si)80 void solist_add_soinfo(soinfo* si) {
81 sonext->next = si;
82 sonext = si;
83 }
84
solist_remove_soinfo(soinfo * si)85 bool solist_remove_soinfo(soinfo* si) {
86 soinfo *prev = nullptr, *trav;
87 for (trav = solist; trav != nullptr; trav = trav->next) {
88 if (trav == si) {
89 break;
90 }
91 prev = trav;
92 }
93
94 if (trav == nullptr) {
95 // si was not in solist
96 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
97 return false;
98 }
99
100 // prev will never be null, because the first entry in solist is
101 // always the static libdl_info.
102 CHECK(prev != nullptr);
103 prev->next = si->next;
104 if (si == sonext) {
105 sonext = prev;
106 }
107
108 return true;
109 }
110
solist_get_head()111 soinfo* solist_get_head() {
112 return solist;
113 }
114
solist_get_somain()115 soinfo* solist_get_somain() {
116 return somain;
117 }
118
solist_get_vdso()119 soinfo* solist_get_vdso() {
120 return vdso;
121 }
122
123 bool g_is_ldd;
124 int g_ld_debug_verbosity;
125
126 static std::vector<std::string> g_ld_preload_names;
127
128 static std::vector<soinfo*> g_ld_preloads;
129
parse_path(const char * path,const char * delimiters,std::vector<std::string> * resolved_paths)130 static void parse_path(const char* path, const char* delimiters,
131 std::vector<std::string>* resolved_paths) {
132 std::vector<std::string> paths;
133 split_path(path, delimiters, &paths);
134 resolve_paths(paths, resolved_paths);
135 }
136
parse_LD_LIBRARY_PATH(const char * path)137 static void parse_LD_LIBRARY_PATH(const char* path) {
138 std::vector<std::string> ld_libary_paths;
139 parse_path(path, ":", &ld_libary_paths);
140 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
141 }
142
parse_LD_PRELOAD(const char * path)143 static void parse_LD_PRELOAD(const char* path) {
144 g_ld_preload_names.clear();
145 if (path != nullptr) {
146 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
147 g_ld_preload_names = android::base::Split(path, " :");
148 g_ld_preload_names.erase(std::remove_if(g_ld_preload_names.begin(), g_ld_preload_names.end(),
149 [](const std::string& s) { return s.empty(); }),
150 g_ld_preload_names.end());
151 }
152 }
153
154 // An empty list of soinfos
155 static soinfo_list_t g_empty_list;
156
add_vdso()157 static void add_vdso() {
158 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
159 if (ehdr_vdso == nullptr) {
160 return;
161 }
162
163 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
164
165 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
166 si->phnum = ehdr_vdso->e_phnum;
167 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
168 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
169 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
170
171 si->prelink_image();
172 si->link_image(SymbolLookupList(si), si, nullptr, nullptr);
173 // prevents accidental unloads...
174 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
175 si->set_linked();
176 si->call_constructors();
177
178 vdso = si;
179 }
180
181 // Initializes an soinfo's link_map_head field using other fields from the
182 // soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
183 // this function is called.
init_link_map_head(soinfo & info)184 static void init_link_map_head(soinfo& info) {
185 auto& map = info.link_map_head;
186 map.l_addr = info.load_bias;
187 map.l_name = const_cast<char*>(info.get_realpath());
188 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
189 }
190
191 extern "C" int __system_properties_init(void);
192
193 struct ExecutableInfo {
194 std::string path;
195 struct stat file_stat;
196 const ElfW(Phdr)* phdr;
197 size_t phdr_count;
198 ElfW(Addr) entry_point;
199 };
200
get_executable_info()201 static ExecutableInfo get_executable_info() {
202 ExecutableInfo result = {};
203
204 if (is_first_stage_init()) {
205 // /proc fs is not mounted when first stage init starts. Therefore we can't
206 // use /proc/self/exe for init.
207 stat("/init", &result.file_stat);
208
209 // /init may be a symlink, so try to read it as such.
210 char path[PATH_MAX];
211 ssize_t path_len = readlink("/init", path, sizeof(path));
212 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
213 result.path = "/init";
214 } else {
215 result.path = std::string(path, path_len);
216 }
217 } else {
218 // Stat "/proc/self/exe" instead of executable_path because
219 // the executable could be unlinked by this point and it should
220 // not cause a crash (see http://b/31084669)
221 if (TEMP_FAILURE_RETRY(stat("/proc/self/exe", &result.file_stat)) != 0) {
222 async_safe_fatal("unable to stat \"/proc/self/exe\": %s", strerror(errno));
223 }
224 char path[PATH_MAX];
225 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
226 if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
227 async_safe_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
228 }
229 result.path = std::string(path, path_len);
230 }
231
232 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
233 result.phdr_count = getauxval(AT_PHNUM);
234 result.entry_point = getauxval(AT_ENTRY);
235 return result;
236 }
237
238 #if defined(__LP64__)
239 static char kFallbackLinkerPath[] = "/system/bin/linker64";
240 #else
241 static char kFallbackLinkerPath[] = "/system/bin/linker";
242 #endif
243
244 __printflike(1, 2)
__linker_error(const char * fmt,...)245 static void __linker_error(const char* fmt, ...) {
246 va_list ap;
247
248 va_start(ap, fmt);
249 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
250 va_end(ap);
251
252 va_start(ap, fmt);
253 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
254 va_end(ap);
255
256 _exit(EXIT_FAILURE);
257 }
258
__linker_cannot_link(const char * argv0)259 static void __linker_cannot_link(const char* argv0) {
260 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s\n",
261 argv0,
262 linker_get_error_buffer());
263 }
264
265 // Load an executable. Normally the kernel has already loaded the executable when the linker
266 // starts. The linker can be invoked directly on an executable, though, and then the linker must
267 // load it. This function doesn't load dependencies or resolve relocations.
load_executable(const char * orig_path)268 static ExecutableInfo load_executable(const char* orig_path) {
269 ExecutableInfo result = {};
270
271 if (orig_path[0] != '/') {
272 __linker_error("error: expected absolute path: \"%s\"\n", orig_path);
273 }
274
275 off64_t file_offset;
276 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
277 if (fd.get() == -1) {
278 __linker_error("error: unable to open file \"%s\"\n", orig_path);
279 }
280
281 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
282 __linker_error("error: unable to stat \"%s\": %s\n", result.path.c_str(), strerror(errno));
283 }
284
285 ElfReader elf_reader;
286 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
287 __linker_error("error: %s\n", linker_get_error_buffer());
288 }
289 address_space_params address_space;
290 if (!elf_reader.Load(&address_space)) {
291 __linker_error("error: %s\n", linker_get_error_buffer());
292 }
293
294 result.phdr = elf_reader.loaded_phdr();
295 result.phdr_count = elf_reader.phdr_count();
296 result.entry_point = elf_reader.entry_point();
297 return result;
298 }
299
linker_main(KernelArgumentBlock & args,const char * exe_to_load)300 static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
301 ProtectedDataGuard guard;
302
303 #if TIMING
304 struct timeval t0, t1;
305 gettimeofday(&t0, 0);
306 #endif
307
308 // Sanitize the environment.
309 __libc_init_AT_SECURE(args.envp);
310
311 // Initialize system properties
312 __system_properties_init(); // may use 'environ'
313
314 // Register the debuggerd signal handler.
315 linker_debuggerd_init();
316
317 g_linker_logger.ResetState();
318
319 // Get a few environment variables.
320 const char* LD_DEBUG = getenv("LD_DEBUG");
321 if (LD_DEBUG != nullptr) {
322 g_ld_debug_verbosity = atoi(LD_DEBUG);
323 }
324
325 #if defined(__LP64__)
326 INFO("[ Android dynamic linker (64-bit) ]");
327 #else
328 INFO("[ Android dynamic linker (32-bit) ]");
329 #endif
330
331 // These should have been sanitized by __libc_init_AT_SECURE, but the test
332 // doesn't cost us anything.
333 const char* ldpath_env = nullptr;
334 const char* ldpreload_env = nullptr;
335 if (!getauxval(AT_SECURE)) {
336 ldpath_env = getenv("LD_LIBRARY_PATH");
337 if (ldpath_env != nullptr) {
338 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
339 }
340 ldpreload_env = getenv("LD_PRELOAD");
341 if (ldpreload_env != nullptr) {
342 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
343 }
344 }
345
346 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
347 get_executable_info();
348
349 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
350
351 // Initialize the main exe's soinfo.
352 soinfo* si = soinfo_alloc(&g_default_namespace,
353 exe_info.path.c_str(), &exe_info.file_stat,
354 0, RTLD_GLOBAL);
355 somain = si;
356 si->phdr = exe_info.phdr;
357 si->phnum = exe_info.phdr_count;
358 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
359 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
360 si->dynamic = nullptr;
361 si->set_main_executable();
362 init_link_map_head(*si);
363
364 set_bss_vma_name(si);
365
366 // Use the executable's PT_INTERP string as the solinker filename in the
367 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
368 // and if the paths for the linker are different, gdb will report that the
369 // PT_INTERP linker path was unloaded once the module list is initialized.
370 // There are three situations to handle:
371 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
372 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
373 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
374 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
375 somain->load_bias);
376 if (interp == nullptr) {
377 // This case can happen if the linker attempts to execute itself
378 // (e.g. "linker64 /system/bin/linker64").
379 interp = kFallbackLinkerPath;
380 }
381 solinker->set_realpath(interp);
382 init_link_map_head(*solinker);
383
384 // Register the main executable and the linker upfront to have
385 // gdb aware of them before loading the rest of the dependency
386 // tree.
387 //
388 // gdb expects the linker to be in the debug shared object list.
389 // Without this, gdb has trouble locating the linker's ".text"
390 // and ".plt" sections. Gdb could also potentially use this to
391 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
392 //
393 insert_link_map_into_debug_map(&si->link_map_head);
394 insert_link_map_into_debug_map(&solinker->link_map_head);
395
396 add_vdso();
397
398 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
399
400 // We haven't supported non-PIE since Lollipop for security reasons.
401 if (elf_hdr->e_type != ET_DYN) {
402 // We don't use async_safe_fatal here because we don't want a tombstone:
403 // even after several years we still find ourselves on app compatibility
404 // investigations because some app's trying to launch an executable that
405 // hasn't worked in at least three years, and we've "helpfully" dropped a
406 // tombstone for them. The tombstone never provided any detail relevant to
407 // fixing the problem anyway, and the utility of drawing extra attention
408 // to the problem is non-existent at this late date.
409 async_safe_format_fd(STDERR_FILENO,
410 "\"%s\": error: Android 5.0 and later only support "
411 "position-independent executables (-fPIE).\n",
412 g_argv[0]);
413 _exit(EXIT_FAILURE);
414 }
415
416 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
417 parse_LD_LIBRARY_PATH(ldpath_env);
418 parse_LD_PRELOAD(ldpreload_env);
419
420 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
421
422 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
423
424 // add somain to global group
425 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
426 // ... and add it to all other linked namespaces
427 for (auto linked_ns : namespaces) {
428 if (linked_ns != &g_default_namespace) {
429 linked_ns->add_soinfo(somain);
430 somain->add_secondary_namespace(linked_ns);
431 }
432 }
433
434 linker_setup_exe_static_tls(g_argv[0]);
435
436 // Load ld_preloads and dependencies.
437 std::vector<const char*> needed_library_name_list;
438 size_t ld_preloads_count = 0;
439
440 for (const auto& ld_preload_name : g_ld_preload_names) {
441 needed_library_name_list.push_back(ld_preload_name.c_str());
442 ++ld_preloads_count;
443 }
444
445 for_each_dt_needed(si, [&](const char* name) {
446 needed_library_name_list.push_back(name);
447 });
448
449 const char** needed_library_names = &needed_library_name_list[0];
450 size_t needed_libraries_count = needed_library_name_list.size();
451
452 if (needed_libraries_count > 0 &&
453 !find_libraries(&g_default_namespace,
454 si,
455 needed_library_names,
456 needed_libraries_count,
457 nullptr,
458 &g_ld_preloads,
459 ld_preloads_count,
460 RTLD_GLOBAL,
461 nullptr,
462 true /* add_as_children */,
463 &namespaces)) {
464 __linker_cannot_link(g_argv[0]);
465 } else if (needed_libraries_count == 0) {
466 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
467 __linker_cannot_link(g_argv[0]);
468 }
469 si->increment_ref_count();
470 }
471
472 linker_finalize_static_tls();
473 __libc_init_main_thread_final();
474
475 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
476
477 si->call_pre_init_constructors();
478 si->call_constructors();
479
480 #if TIMING
481 gettimeofday(&t1, nullptr);
482 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
483 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
484 static_cast<long long>(t1.tv_usec)) -
485 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
486 static_cast<long long>(t0.tv_usec))));
487 #endif
488 #if STATS
489 print_linker_stats();
490 #endif
491 #if TIMING || STATS
492 fflush(stdout);
493 #endif
494
495 // We are about to hand control over to the executable loaded. We don't want
496 // to leave dirty pages behind unnecessarily.
497 purge_unused_memory();
498
499 ElfW(Addr) entry = exe_info.entry_point;
500 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
501 return entry;
502 }
503
504 /* Compute the load-bias of an existing executable. This shall only
505 * be used to compute the load bias of an executable or shared library
506 * that was loaded by the kernel itself.
507 *
508 * Input:
509 * elf -> address of ELF header, assumed to be at the start of the file.
510 * Return:
511 * load bias, i.e. add the value of any p_vaddr in the file to get
512 * the corresponding address in memory.
513 */
get_elf_exec_load_bias(const ElfW (Ehdr)* elf)514 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
515 ElfW(Addr) offset = elf->e_phoff;
516 const ElfW(Phdr)* phdr_table =
517 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
518 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
519
520 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
521 if (phdr->p_type == PT_LOAD) {
522 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
523 }
524 }
525 return 0;
526 }
527
528 /* Find the load bias and base address of an executable or shared object loaded
529 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
530 *
531 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
532 */
get_elf_base_from_phdr(const ElfW (Phdr)* phdr_table,size_t phdr_count,ElfW (Addr)* base,ElfW (Addr)* load_bias)533 static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
534 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
535 for (size_t i = 0; i < phdr_count; ++i) {
536 if (phdr_table[i].p_type == PT_PHDR) {
537 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
538 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
539 return;
540 }
541 }
542 async_safe_fatal("Could not find a PHDR: broken executable?");
543 }
544
545 /*
546 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
547 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
548 * namely the linker itself and the main executable.
549 */
set_bss_vma_name(soinfo * si)550 static void set_bss_vma_name(soinfo* si) {
551 for (size_t i = 0; i < si->phnum; ++i) {
552 auto phdr = &si->phdr[i];
553
554 if (phdr->p_type != PT_LOAD) {
555 continue;
556 }
557
558 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
559 ElfW(Addr) seg_page_end = PAGE_END(seg_start + phdr->p_memsz);
560 ElfW(Addr) seg_file_end = PAGE_END(seg_start + phdr->p_filesz);
561
562 if (seg_page_end > seg_file_end) {
563 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
564 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
565 ".bss");
566 }
567 }
568 }
569
570 // TODO: There is a similar ifunc resolver calling loop in libc_init_static.cpp, but that version
571 // uses weak symbols, which don't work in the linker prior to its relocation. This version also
572 // supports a load bias. When we stop supporting the gold linker in the NDK, then maybe we can use
573 // non-weak definitions and merge the two loops.
574 #if defined(USE_RELA)
575 extern __LIBC_HIDDEN__ ElfW(Rela) __rela_iplt_start[], __rela_iplt_end[];
576
call_ifunc_resolvers(ElfW (Addr)load_bias)577 static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
578 for (ElfW(Rela) *r = __rela_iplt_start; r != __rela_iplt_end; ++r) {
579 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
580 ElfW(Addr) resolver = r->r_addend + load_bias;
581 *offset = __bionic_call_ifunc_resolver(resolver);
582 }
583 }
584 #else
585 extern __LIBC_HIDDEN__ ElfW(Rel) __rel_iplt_start[], __rel_iplt_end[];
586
call_ifunc_resolvers(ElfW (Addr)load_bias)587 static void call_ifunc_resolvers(ElfW(Addr) load_bias) {
588 for (ElfW(Rel) *r = __rel_iplt_start; r != __rel_iplt_end; ++r) {
589 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(r->r_offset + load_bias);
590 ElfW(Addr) resolver = *offset + load_bias;
591 *offset = __bionic_call_ifunc_resolver(resolver);
592 }
593 }
594 #endif
595
596 // Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
linker_memclr(void * dst,size_t cnt)597 static void linker_memclr(void* dst, size_t cnt) {
598 for (size_t i = 0; i < cnt; ++i) {
599 reinterpret_cast<char*>(dst)[i] = '\0';
600 }
601 }
602
603 // Detect an attempt to run the linker on itself. e.g.:
604 // /system/bin/linker64 /system/bin/linker64
605 // Use priority-1 to run this constructor before other constructors.
detect_self_exec()606 __attribute__((constructor(1))) static void detect_self_exec() {
607 // Normally, the linker initializes the auxv global before calling its
608 // constructors. If the linker loads itself, though, the first loader calls
609 // the second loader's constructors before calling __linker_init.
610 if (__libc_shared_globals()->auxv != nullptr) {
611 return;
612 }
613 #if defined(__i386__)
614 // We don't have access to the auxv struct from here, so use the int 0x80
615 // fallback.
616 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
617 #endif
618 __linker_error("error: linker cannot load itself\n");
619 }
620
621 static ElfW(Addr) __attribute__((noinline))
622 __linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
623
624 /*
625 * This is the entry point for the linker, called from begin.S. This
626 * method is responsible for fixing the linker's own relocations, and
627 * then calling __linker_init_post_relocation().
628 *
629 * Because this method is called before the linker has fixed it's own
630 * relocations, any attempt to reference an extern variable, extern
631 * function, or other GOT reference will generate a segfault.
632 */
__linker_init(void * raw_args)633 extern "C" ElfW(Addr) __linker_init(void* raw_args) {
634 // Initialize TLS early so system calls and errno work.
635 KernelArgumentBlock args(raw_args);
636 bionic_tcb temp_tcb __attribute__((uninitialized));
637 linker_memclr(&temp_tcb, sizeof(temp_tcb));
638 __libc_init_main_thread_early(args, &temp_tcb);
639
640 // When the linker is run by itself (rather than as an interpreter for
641 // another program), AT_BASE is 0.
642 ElfW(Addr) linker_addr = getauxval(AT_BASE);
643 if (linker_addr == 0) {
644 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
645 // the phdr to find the linker's base address.
646 ElfW(Addr) load_bias;
647 get_elf_base_from_phdr(
648 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
649 &linker_addr, &load_bias);
650 }
651
652 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
653 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
654
655 // string.h functions must not be used prior to calling the linker's ifunc resolvers.
656 const ElfW(Addr) load_bias = get_elf_exec_load_bias(elf_hdr);
657 call_ifunc_resolvers(load_bias);
658
659 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
660
661 tmp_linker_so.base = linker_addr;
662 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
663 tmp_linker_so.load_bias = load_bias;
664 tmp_linker_so.dynamic = nullptr;
665 tmp_linker_so.phdr = phdr;
666 tmp_linker_so.phnum = elf_hdr->e_phnum;
667 tmp_linker_so.set_linker_flag();
668
669 // Prelink the linker so we can access linker globals.
670 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
671 if (!tmp_linker_so.link_image(SymbolLookupList(&tmp_linker_so), &tmp_linker_so, nullptr, nullptr)) __linker_cannot_link(args.argv[0]);
672
673 return __linker_init_post_relocation(args, tmp_linker_so);
674 }
675
676 /*
677 * This code is called after the linker has linked itself and fixed its own
678 * GOT. It is safe to make references to externs and other non-local data at
679 * this point. The compiler sometimes moves GOT references earlier in a
680 * function, so avoid inlining this function (http://b/80503879).
681 */
682 static ElfW(Addr) __attribute__((noinline))
__linker_init_post_relocation(KernelArgumentBlock & args,soinfo & tmp_linker_so)683 __linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
684 // Finish initializing the main thread.
685 __libc_init_main_thread_late();
686
687 // We didn't protect the linker's RELRO pages in link_image because we
688 // couldn't make system calls on x86 at that point, but we can now...
689 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
690
691 // And we can set VMA name for the bss section now
692 set_bss_vma_name(&tmp_linker_so);
693
694 // Initialize the linker's static libc's globals
695 __libc_init_globals();
696
697 // Initialize the linker's own global variables
698 tmp_linker_so.call_constructors();
699
700 // When the linker is run directly rather than acting as PT_INTERP, parse
701 // arguments and determine the executable to load. When it's instead acting
702 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
703 // linker's _start.
704 const char* exe_to_load = nullptr;
705 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
706 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
707 // We're being asked to behave like ldd(1).
708 g_is_ldd = true;
709 exe_to_load = args.argv[2];
710 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
711 async_safe_format_fd(STDOUT_FILENO,
712 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
713 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
714 "\n"
715 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
716 "this program because it's the PT_INTERP of a dynamic executable.\n"
717 "\n"
718 "This program can also be run directly to load and run a dynamic executable. The\n"
719 "executable can be inside a zip file if it's stored uncompressed and at a\n"
720 "page-aligned offset.\n"
721 "\n"
722 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
723 args.argv[0], args.argv[0]);
724 _exit(EXIT_SUCCESS);
725 } else {
726 exe_to_load = args.argv[1];
727 __libc_shared_globals()->initial_linker_arg_count = 1;
728 }
729 }
730
731 // store argc/argv/envp to use them for calling constructors
732 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
733 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
734 g_envp = args.envp;
735 __libc_shared_globals()->init_progname = g_argv[0];
736
737 // Initialize static variables. Note that in order to
738 // get correct libdl_info we need to call constructors
739 // before get_libdl_info().
740 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
741 g_default_namespace.add_soinfo(solinker);
742
743 ElfW(Addr) start_address = linker_main(args, exe_to_load);
744
745 if (g_is_ldd) _exit(EXIT_SUCCESS);
746
747 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
748
749 // Return the address that the calling assembly stub should jump to.
750 return start_address;
751 }
752