1 /* $NetBSD: rtld.c,v 1.217 2024/01/19 19:21:34 christos Exp $ */
2
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt@3am-software.com>
6 * Copyright 2002 Charles M. Hannum <root@ihack.net>
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by John Polstra.
20 * 4. The name of the author may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /*
36 * Dynamic linker for ELF.
37 *
38 * John Polstra <jdp@polstra.com>.
39 */
40
41 #include <sys/cdefs.h>
42 #ifndef lint
43 __RCSID("$NetBSD: rtld.c,v 1.217 2024/01/19 19:21:34 christos Exp $");
44 #endif /* not lint */
45
46 #include <sys/param.h>
47 #include <sys/atomic.h>
48 #include <sys/mman.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <lwp.h>
53 #include <stdarg.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <dirent.h>
59
60 #include <ctype.h>
61
62 #include <dlfcn.h>
63
64 #include "debug.h"
65 #include "hash.h"
66 #include "rtld.h"
67
68 #if !defined(lint)
69 #include "sysident.h"
70 #endif
71
72 /*
73 * Hidden function from common/lib/libc/atomic - nop on machines
74 * with enough atomic ops. Need to explicitly call it early.
75 * libc has the same symbol and will initialize itself, but not our copy.
76 */
77 void __libc_atomic_init(void);
78
79 /*
80 * Function declarations.
81 */
82 static void _rtld_init(caddr_t, caddr_t, const char *);
83 static void _rtld_exit(void);
84
85 Elf_Addr _rtld(Elf_Addr *, Elf_Addr);
86
87
88 /*
89 * Data declarations.
90 */
91 static char *error_message; /* Message for dlopen(), or NULL */
92
93 struct r_debug _rtld_debug; /* The SVR4 interface for the debugger */
94 bool _rtld_trust; /* False for setuid and setgid programs */
95 Obj_Entry *_rtld_objlist; /* Head of linked list of shared objects */
96 Obj_Entry **_rtld_objtail; /* Link field of last object in list */
97 Obj_Entry *_rtld_objmain; /* The main program shared object */
98 Obj_Entry _rtld_objself; /* The dynamic linker shared object */
99 u_int _rtld_objcount; /* Number of objects in _rtld_objlist */
100 u_int _rtld_objloads; /* Number of objects loaded in _rtld_objlist */
101 u_int _rtld_objgen; /* Generation count for _rtld_objlist */
102 const char _rtld_path[] = _PATH_RTLD;
103
104 /* Initialize a fake symbol for resolving undefined weak references. */
105 Elf_Sym _rtld_sym_zero = {
106 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
107 .st_shndx = SHN_ABS,
108 };
109 size_t _rtld_pagesz; /* Page size, as provided by kernel */
110
111 Search_Path *_rtld_default_paths;
112 Search_Path *_rtld_paths;
113
114 Library_Xform *_rtld_xforms;
115 static void *auxinfo;
116
117 /*
118 * Global declarations normally provided by crt0.
119 */
120 char *__progname;
121 char **environ;
122
123 static volatile bool _rtld_mutex_may_recurse;
124
125 #if defined(RTLD_DEBUG)
126 #ifndef __sh__
127 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
128 #else /* 32-bit SuperH */
129 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
130 #endif
131 #endif /* RTLD_DEBUG */
132 extern Elf_Dyn _DYNAMIC;
133
134 static void _rtld_call_fini_functions(sigset_t *, int);
135 static void _rtld_call_init_functions(sigset_t *);
136 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
137 static void _rtld_initlist_tsort(Objlist *, int);
138 static Obj_Entry *_rtld_dlcheck(void *);
139 static void _rtld_init_dag(Obj_Entry *);
140 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
141 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
142 static void _rtld_objlist_clear(Objlist *);
143 static void _rtld_unload_object(sigset_t *, Obj_Entry *, bool);
144 static void _rtld_unref_dag(Obj_Entry *);
145 static Obj_Entry *_rtld_obj_from_addr(const void *);
146 static void _rtld_fill_dl_phdr_info(const Obj_Entry *, struct dl_phdr_info *);
147
148 static inline void
_rtld_call_initfini_function(fptr_t func,sigset_t * mask)149 _rtld_call_initfini_function(fptr_t func, sigset_t *mask)
150 {
151 _rtld_exclusive_exit(mask);
152 (*func)();
153 _rtld_exclusive_enter(mask);
154 }
155
156 static void
_rtld_call_fini_function(Obj_Entry * obj,sigset_t * mask,u_int cur_objgen)157 _rtld_call_fini_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
158 {
159 if (obj->fini_arraysz == 0 && (obj->fini == NULL || obj->fini_called))
160 return;
161
162 if (obj->fini != NULL && !obj->fini_called) {
163 dbg (("calling fini function %s at %p%s", obj->path,
164 (void *)obj->fini,
165 obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
166 obj->fini_called = 1;
167 _rtld_call_initfini_function(obj->fini, mask);
168 }
169 #ifdef HAVE_INITFINI_ARRAY
170 /*
171 * Now process the fini_array if it exists. Simply go from
172 * start to end. We need to make restartable so just advance
173 * the array pointer and decrement the size each time through
174 * the loop.
175 */
176 while (obj->fini_arraysz > 0 && _rtld_objgen == cur_objgen) {
177 fptr_t fini = *obj->fini_array++;
178 obj->fini_arraysz--;
179 dbg (("calling fini array function %s at %p%s", obj->path,
180 (void *)fini,
181 obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
182 _rtld_call_initfini_function(fini, mask);
183 }
184 #endif /* HAVE_INITFINI_ARRAY */
185 }
186
187 static void
_rtld_call_fini_functions(sigset_t * mask,int force)188 _rtld_call_fini_functions(sigset_t *mask, int force)
189 {
190 Objlist_Entry *elm;
191 Objlist finilist;
192 u_int cur_objgen;
193
194 dbg(("_rtld_call_fini_functions(%d)", force));
195
196 restart:
197 cur_objgen = ++_rtld_objgen;
198 SIMPLEQ_INIT(&finilist);
199 _rtld_initlist_tsort(&finilist, 1);
200
201 /* First pass: objects _not_ marked with DF_1_INITFIRST. */
202 SIMPLEQ_FOREACH(elm, &finilist, link) {
203 Obj_Entry * const obj = elm->obj;
204 if (!obj->z_initfirst) {
205 if (obj->refcount > 0 && !force) {
206 continue;
207 }
208 /*
209 * XXX This can race against a concurrent dlclose().
210 * XXX In that case, the object could be unmapped before
211 * XXX the fini() call or the fini_array has completed.
212 */
213 _rtld_call_fini_function(obj, mask, cur_objgen);
214 if (_rtld_objgen != cur_objgen) {
215 dbg(("restarting fini iteration"));
216 _rtld_objlist_clear(&finilist);
217 goto restart;
218 }
219 }
220 }
221
222 /* Second pass: objects marked with DF_1_INITFIRST. */
223 SIMPLEQ_FOREACH(elm, &finilist, link) {
224 Obj_Entry * const obj = elm->obj;
225 if (obj->refcount > 0 && !force) {
226 continue;
227 }
228 /* XXX See above for the race condition here */
229 _rtld_call_fini_function(obj, mask, cur_objgen);
230 if (_rtld_objgen != cur_objgen) {
231 dbg(("restarting fini iteration"));
232 _rtld_objlist_clear(&finilist);
233 goto restart;
234 }
235 }
236
237 _rtld_objlist_clear(&finilist);
238 }
239
240 static void
_rtld_call_init_function(Obj_Entry * obj,sigset_t * mask,u_int cur_objgen)241 _rtld_call_init_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
242 {
243 if (obj->init_arraysz == 0 && (obj->init_called || obj->init == NULL))
244 return;
245
246 if (!obj->init_called && obj->init != NULL) {
247 dbg (("calling init function %s at %p%s",
248 obj->path, (void *)obj->init,
249 obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
250 obj->init_called = 1;
251 _rtld_call_initfini_function(obj->init, mask);
252 }
253
254 #ifdef HAVE_INITFINI_ARRAY
255 /*
256 * Now process the init_array if it exists. Simply go from
257 * start to end. We need to make restartable so just advance
258 * the array pointer and decrement the size each time through
259 * the loop.
260 */
261 while (obj->init_arraysz > 0 && _rtld_objgen == cur_objgen) {
262 fptr_t init = *obj->init_array++;
263 obj->init_arraysz--;
264 dbg (("calling init_array function %s at %p%s",
265 obj->path, (void *)init,
266 obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
267 _rtld_call_initfini_function(init, mask);
268 }
269 #endif /* HAVE_INITFINI_ARRAY */
270 }
271
272 static bool
_rtld_call_ifunc_functions(sigset_t * mask,Obj_Entry * obj,u_int cur_objgen)273 _rtld_call_ifunc_functions(sigset_t *mask, Obj_Entry *obj, u_int cur_objgen)
274 {
275 if (obj->ifunc_remaining
276 #if defined(IFUNC_NONPLT)
277 || obj->ifunc_remaining_nonplt
278 #endif
279 ) {
280 _rtld_call_ifunc(obj, mask, cur_objgen);
281 if (_rtld_objgen != cur_objgen) {
282 return true;
283 }
284 }
285 return false;
286 }
287
288 static void
_rtld_call_init_functions(sigset_t * mask)289 _rtld_call_init_functions(sigset_t *mask)
290 {
291 Objlist_Entry *elm;
292 Objlist initlist;
293 u_int cur_objgen;
294
295 dbg(("_rtld_call_init_functions()"));
296
297 restart:
298 cur_objgen = ++_rtld_objgen;
299 SIMPLEQ_INIT(&initlist);
300 _rtld_initlist_tsort(&initlist, 0);
301
302 /* First pass: objects with IRELATIVE relocations. */
303 SIMPLEQ_FOREACH(elm, &initlist, link) {
304 if (_rtld_call_ifunc_functions(mask, elm->obj, cur_objgen)) {
305 dbg(("restarting init iteration"));
306 _rtld_objlist_clear(&initlist);
307 goto restart;
308 }
309 }
310 /*
311 * XXX: For historic reasons, init/fini of the main object are called
312 * from crt0. Don't introduce that mistake for ifunc, so look at
313 * the head of _rtld_objlist that _rtld_initlist_tsort skipped.
314 */
315 if (_rtld_call_ifunc_functions(mask, _rtld_objlist, cur_objgen)) {
316 dbg(("restarting init iteration"));
317 _rtld_objlist_clear(&initlist);
318 goto restart;
319 }
320
321 /* Second pass: objects marked with DF_1_INITFIRST. */
322 SIMPLEQ_FOREACH(elm, &initlist, link) {
323 Obj_Entry * const obj = elm->obj;
324 if (obj->z_initfirst) {
325 _rtld_call_init_function(obj, mask, cur_objgen);
326 if (_rtld_objgen != cur_objgen) {
327 dbg(("restarting init iteration"));
328 _rtld_objlist_clear(&initlist);
329 goto restart;
330 }
331 }
332 }
333
334 /* Third pass: all other objects. */
335 SIMPLEQ_FOREACH(elm, &initlist, link) {
336 _rtld_call_init_function(elm->obj, mask, cur_objgen);
337 if (_rtld_objgen != cur_objgen) {
338 dbg(("restarting init iteration"));
339 _rtld_objlist_clear(&initlist);
340 goto restart;
341 }
342 }
343
344 _rtld_objlist_clear(&initlist);
345 }
346
347 /*
348 * Initialize the dynamic linker. The argument is the address at which
349 * the dynamic linker has been mapped into memory. The primary task of
350 * this function is to create an Obj_Entry for the dynamic linker and
351 * to resolve the PLT relocation for platforms that need it (those that
352 * define __HAVE_FUNCTION_DESCRIPTORS
353 */
354 static void
_rtld_init(caddr_t mapbase,caddr_t relocbase,const char * execname)355 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
356 {
357 const Elf_Ehdr *ehdr;
358
359 /* Conjure up an Obj_Entry structure for the dynamic linker. */
360 _rtld_objself.path = __UNCONST(_rtld_path);
361 _rtld_objself.pathlen = sizeof(_rtld_path)-1;
362 _rtld_objself.rtld = true;
363 _rtld_objself.mapbase = mapbase;
364 _rtld_objself.relocbase = relocbase;
365 _rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
366 _rtld_objself.strtab = "_rtld_sym_zero";
367
368 /*
369 * Set value to -relocbase so that
370 *
371 * _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
372 *
373 * This allows unresolved references to weak symbols to be computed
374 * to a value of 0.
375 */
376 _rtld_sym_zero.st_value = -(uintptr_t)relocbase;
377
378 _rtld_digest_dynamic(_rtld_path, &_rtld_objself);
379 assert(!_rtld_objself.needed);
380 #if !defined(__hppa__)
381 assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
382 #else
383 _rtld_relocate_plt_objects(&_rtld_objself);
384 #endif
385 #if !defined(__mips__) && !defined(__hppa__)
386 assert(!_rtld_objself.pltgot);
387 #endif
388 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
389 /* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
390 assert(!_rtld_objself.textrel);
391 #endif
392
393 _rtld_add_paths(execname, &_rtld_default_paths,
394 RTLD_DEFAULT_LIBRARY_PATH);
395
396 #ifdef RTLD_ARCH_SUBDIR
397 _rtld_add_paths(execname, &_rtld_default_paths,
398 RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
399 #endif
400
401 /* Make the object list empty. */
402 _rtld_objlist = NULL;
403 _rtld_objtail = &_rtld_objlist;
404 _rtld_objcount = 0;
405
406 _rtld_debug.r_version = R_DEBUG_VERSION;
407 _rtld_debug.r_brk = _rtld_debug_state;
408 _rtld_debug.r_state = RT_CONSISTENT;
409 _rtld_debug.r_ldbase = _rtld_objself.relocbase;
410
411 ehdr = (Elf_Ehdr *)mapbase;
412 _rtld_objself.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
413 _rtld_objself.phsize = ehdr->e_phnum * sizeof(_rtld_objself.phdr[0]);
414
415 __libc_atomic_init();
416 }
417
418 /*
419 * Cleanup procedure. It will be called (by the atexit() mechanism) just
420 * before the process exits.
421 */
422 static void
_rtld_exit(void)423 _rtld_exit(void)
424 {
425 sigset_t mask;
426
427 dbg(("rtld_exit()"));
428
429 _rtld_exclusive_enter(&mask);
430
431 _rtld_call_fini_functions(&mask, 1);
432
433 _rtld_exclusive_exit(&mask);
434 }
435
436 __dso_public void *
_dlauxinfo(void)437 _dlauxinfo(void)
438 {
439 return auxinfo;
440 }
441
442 /*
443 * Main entry point for dynamic linking. The argument is the stack
444 * pointer. The stack is expected to be laid out as described in the
445 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
446 * the stack pointer points to a word containing ARGC. Following that
447 * in the stack is a null-terminated sequence of pointers to argument
448 * strings. Then comes a null-terminated sequence of pointers to
449 * environment strings. Finally, there is a sequence of "auxiliary
450 * vector" entries.
451 *
452 * This function returns the entry point for the main program, the dynamic
453 * linker's exit procedure in sp[0], and a pointer to the main object in
454 * sp[1].
455 */
456 Elf_Addr
_rtld(Elf_Addr * sp,Elf_Addr relocbase)457 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
458 {
459 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
460 *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
461 *pAUX_ruid, *pAUX_rgid;
462 const AuxInfo *pAUX_pagesz;
463 char **env, **oenvp;
464 const AuxInfo *auxp;
465 Obj_Entry *obj;
466 Elf_Addr *const osp = sp;
467 bool bind_now = 0;
468 const char *ld_bind_now, *ld_preload, *ld_library_path;
469 const char **argv;
470 const char *execname;
471 long argc;
472 const char **real___progname;
473 const Obj_Entry **real___mainprog_obj;
474 char ***real_environ;
475 sigset_t mask;
476 #ifdef DEBUG
477 const char *ld_debug;
478 #endif
479 #ifdef RTLD_DEBUG
480 int i = 0;
481 #endif
482
483 /*
484 * On entry, the dynamic linker itself has not been relocated yet.
485 * Be very careful not to reference any global data until after
486 * _rtld_init has returned. It is OK to reference file-scope statics
487 * and string constants, and to call static and global functions.
488 */
489 /* Find the auxiliary vector on the stack. */
490 /* first Elf_Word reserved to address of exit routine */
491 #if defined(RTLD_DEBUG)
492 debug = 1;
493 dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
494 (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
495 #ifndef __x86_64__
496 dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
497 &_DYNAMIC));
498 #endif
499 #endif
500
501 sp += 2; /* skip over return argument space */
502 argv = (const char **) &sp[1];
503 argc = *(long *)sp;
504 sp += 2 + argc; /* Skip over argc, arguments, and NULL
505 * terminator */
506 env = (char **) sp;
507 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
508 #if defined(RTLD_DEBUG)
509 dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
510 #endif
511 }
512 auxinfo = (AuxInfo *) sp;
513
514 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
515 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
516 pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
517 pAUX_pagesz = NULL;
518
519 execname = NULL;
520
521 /* Digest the auxiliary vector. */
522 for (auxp = auxinfo; auxp->a_type != AT_NULL; ++auxp) {
523 switch (auxp->a_type) {
524 case AT_BASE:
525 pAUX_base = auxp;
526 break;
527 case AT_ENTRY:
528 pAUX_entry = auxp;
529 break;
530 case AT_EXECFD:
531 pAUX_execfd = auxp;
532 break;
533 case AT_PHDR:
534 pAUX_phdr = auxp;
535 break;
536 case AT_PHENT:
537 pAUX_phent = auxp;
538 break;
539 case AT_PHNUM:
540 pAUX_phnum = auxp;
541 break;
542 #ifdef AT_EUID
543 case AT_EUID:
544 pAUX_euid = auxp;
545 break;
546 case AT_RUID:
547 pAUX_ruid = auxp;
548 break;
549 case AT_EGID:
550 pAUX_egid = auxp;
551 break;
552 case AT_RGID:
553 pAUX_rgid = auxp;
554 break;
555 #endif
556 #ifdef AT_SUN_EXECNAME
557 case AT_SUN_EXECNAME:
558 execname = (const char *)(const void *)auxp->a_v;
559 break;
560 #endif
561 case AT_PAGESZ:
562 pAUX_pagesz = auxp;
563 break;
564 }
565 }
566
567 /* Initialize and relocate ourselves. */
568 if (pAUX_base == NULL) {
569 _rtld_error("Bad pAUX_base");
570 _rtld_die();
571 }
572 assert(pAUX_pagesz != NULL);
573 _rtld_pagesz = (int)pAUX_pagesz->a_v;
574 _rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
575
576 __progname = _rtld_objself.path;
577 environ = env;
578
579 _rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
580 (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
581 ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
582 (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
583
584 #ifdef DEBUG
585 ld_debug = NULL;
586 #endif
587 ld_bind_now = NULL;
588 ld_library_path = NULL;
589 ld_preload = NULL;
590 /*
591 * Inline avoid using normal getenv/unsetenv here as the libc
592 * code is quite a bit more complicated.
593 */
594 for (oenvp = env; *env != NULL; ++env) {
595 static const char bind_var[] = "LD_BIND_NOW=";
596 static const char debug_var[] = "LD_DEBUG=";
597 static const char path_var[] = "LD_LIBRARY_PATH=";
598 static const char preload_var[] = "LD_PRELOAD=";
599 #define LEN(x) (sizeof(x) - 1)
600
601 if ((*env)[0] != 'L' || (*env)[1] != 'D') {
602 /*
603 * Special case to skip most entries without
604 * the more expensive calls to strncmp.
605 */
606 *oenvp++ = *env;
607 } else if (strncmp(*env, debug_var, LEN(debug_var)) == 0) {
608 if (_rtld_trust) {
609 #ifdef DEBUG
610 ld_debug = *env + LEN(debug_var);
611 #endif
612 *oenvp++ = *env;
613 }
614 } else if (strncmp(*env, bind_var, LEN(bind_var)) == 0) {
615 if (_rtld_trust) {
616 ld_bind_now = *env + LEN(bind_var);
617 *oenvp++ = *env;
618 }
619 } else if (strncmp(*env, path_var, LEN(path_var)) == 0) {
620 if (_rtld_trust) {
621 ld_library_path = *env + LEN(path_var);
622 *oenvp++ = *env;
623 }
624 } else if (strncmp(*env, preload_var, LEN(preload_var)) == 0) {
625 if (_rtld_trust) {
626 ld_preload = *env + LEN(preload_var);
627 *oenvp++ = *env;
628 }
629 } else {
630 *oenvp++ = *env;
631 }
632 #undef LEN
633 }
634 *oenvp++ = NULL;
635
636 if (ld_bind_now != NULL && *ld_bind_now != '\0')
637 bind_now = true;
638 if (_rtld_trust) {
639 #ifdef DEBUG
640 #ifdef RTLD_DEBUG
641 debug = 0;
642 #endif
643 if (ld_debug != NULL && *ld_debug != '\0')
644 debug = 1;
645 #endif
646 _rtld_add_paths(execname, &_rtld_paths, ld_library_path);
647 } else {
648 execname = NULL;
649 }
650 _rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
651 _PATH_LD_HINTS);
652 dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
653 _rtld_objself.mapbase, _rtld_objself.relocbase));
654
655 /*
656 * Load the main program, or process its program header if it is
657 * already loaded.
658 */
659 if (pAUX_execfd != NULL) { /* Load the main program. */
660 int fd = pAUX_execfd->a_v;
661 const char *obj_name = argv[0] ? argv[0] : "main program";
662 dbg(("loading main program"));
663 _rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
664 close(fd);
665 if (_rtld_objmain == NULL)
666 _rtld_die();
667 } else { /* Main program already loaded. */
668 const Elf_Phdr *phdr;
669 int phnum;
670 caddr_t entry;
671
672 dbg(("processing main program's program header"));
673 assert(pAUX_phdr != NULL);
674 phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
675 assert(pAUX_phnum != NULL);
676 phnum = pAUX_phnum->a_v;
677 assert(pAUX_phent != NULL);
678 assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
679 assert(pAUX_entry != NULL);
680 entry = (caddr_t) pAUX_entry->a_v;
681 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
682 _rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
683 "main program");
684 _rtld_objmain->pathlen = strlen(_rtld_objmain->path);
685 }
686
687 _rtld_objmain->mainprog = true;
688
689 /*
690 * Get the actual dynamic linker pathname from the executable if
691 * possible. (It should always be possible.) That ensures that
692 * the debugger will find the right dynamic linker even if a
693 * non-standard one is being used.
694 */
695 if (_rtld_objmain->interp != NULL &&
696 strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
697 _rtld_objself.path = xstrdup(_rtld_objmain->interp);
698 _rtld_objself.pathlen = strlen(_rtld_objself.path);
699 }
700 dbg(("actual dynamic linker is %s", _rtld_objself.path));
701
702 _rtld_digest_dynamic(execname, _rtld_objmain);
703
704 /* Link the main program into the list of objects. */
705 *_rtld_objtail = _rtld_objmain;
706 _rtld_objtail = &_rtld_objmain->next;
707 _rtld_objcount++;
708 _rtld_objloads++;
709
710 _rtld_linkmap_add(_rtld_objmain);
711 _rtld_objself.path = xstrdup(_rtld_objself.path);
712 _rtld_linkmap_add(&_rtld_objself);
713
714 ++_rtld_objmain->refcount;
715 _rtld_objmain->mainref = 1;
716 _rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
717
718 if (ld_preload) {
719 /*
720 * Pre-load user-specified objects after the main program
721 * but before any shared object dependencies.
722 */
723 dbg(("preloading objects"));
724 if (_rtld_preload(ld_preload) == -1)
725 _rtld_die();
726 }
727
728 dbg(("loading needed objects"));
729 if (_rtld_load_needed_objects(_rtld_objmain, _RTLD_MAIN) == -1)
730 _rtld_die();
731
732 dbg(("checking for required versions"));
733 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
734 if (_rtld_verify_object_versions(obj) == -1)
735 _rtld_die();
736 }
737
738 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
739 dbg(("initializing initial Thread Local Storage offsets"));
740 /*
741 * All initial objects get the TLS space from the static block.
742 */
743 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
744 _rtld_tls_offset_allocate(obj);
745 #endif
746
747 dbg(("relocating objects"));
748 if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
749 _rtld_die();
750
751 dbg(("doing copy relocations"));
752 if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
753 _rtld_die();
754
755 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
756 dbg(("initializing Thread Local Storage for main thread"));
757 /*
758 * Set up TLS area for the main thread.
759 * This has to be done after all relocations are processed,
760 * since .tdata may contain relocations.
761 */
762 _rtld_tls_initial_allocation();
763 #endif
764
765 /*
766 * Set the __progname, environ and, __mainprog_obj before
767 * calling anything that might use them.
768 */
769 real___progname = _rtld_objmain_sym("__progname");
770 if (real___progname) {
771 if (argv[0] != NULL) {
772 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
773 (*real___progname) = argv[0];
774 else
775 (*real___progname)++;
776 } else {
777 (*real___progname) = NULL;
778 }
779 }
780 real_environ = _rtld_objmain_sym("environ");
781 if (real_environ)
782 *real_environ = environ;
783 /*
784 * Set __mainprog_obj for old binaries.
785 */
786 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
787 if (real___mainprog_obj)
788 *real___mainprog_obj = _rtld_objmain;
789
790 _rtld_debug_state(); /* say hello to the debugger! */
791
792 _rtld_exclusive_enter(&mask);
793
794 dbg(("calling _init functions"));
795 _rtld_call_init_functions(&mask);
796
797 dbg(("control at program entry point = %p, obj = %p, exit = %p",
798 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
799
800 _rtld_exclusive_exit(&mask);
801
802 /*
803 * Return with the entry point and the exit procedure in at the top
804 * of stack.
805 */
806
807 ((void **) osp)[0] = _rtld_exit;
808 ((void **) osp)[1] = __UNCONST(_rtld_compat_obj);
809 return (Elf_Addr) _rtld_objmain->entry;
810 }
811
812 void
_rtld_die(void)813 _rtld_die(void)
814 {
815 const char *msg = dlerror();
816
817 if (msg == NULL)
818 msg = "Fatal error";
819 xerrx(1, "%s", msg);
820 }
821
822 static Obj_Entry *
_rtld_dlcheck(void * handle)823 _rtld_dlcheck(void *handle)
824 {
825 Obj_Entry *obj;
826
827 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
828 if (obj == (Obj_Entry *) handle)
829 break;
830
831 if (obj == NULL || obj->dl_refcount == 0) {
832 _rtld_error("Invalid shared object handle %p", handle);
833 return NULL;
834 }
835 return obj;
836 }
837
838 static void
_rtld_initlist_visit(Objlist * list,Obj_Entry * obj,int rev)839 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
840 {
841 Needed_Entry* elm;
842
843 /* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
844
845 if (obj->init_done)
846 return;
847 obj->init_done = 1;
848
849 for (elm = obj->needed; elm != NULL; elm = elm->next) {
850 if (elm->obj != NULL) {
851 _rtld_initlist_visit(list, elm->obj, rev);
852 }
853 }
854
855 if (rev) {
856 _rtld_objlist_push_head(list, obj);
857 } else {
858 _rtld_objlist_push_tail(list, obj);
859 }
860 }
861
862 static void
_rtld_initlist_tsort(Objlist * list,int rev)863 _rtld_initlist_tsort(Objlist* list, int rev)
864 {
865 dbg(("_rtld_initlist_tsort"));
866
867 Obj_Entry* obj;
868
869 /*
870 * We don't include objmain here (starting from next)
871 * because csu handles it
872 */
873 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
874 obj->init_done = 0;
875 }
876
877 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
878 _rtld_initlist_visit(list, obj, rev);
879 }
880 }
881
882 static void
_rtld_init_dag(Obj_Entry * root)883 _rtld_init_dag(Obj_Entry *root)
884 {
885
886 _rtld_init_dag1(root, root);
887 }
888
889 static void
_rtld_init_dag1(Obj_Entry * root,Obj_Entry * obj)890 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
891 {
892 const Needed_Entry *needed;
893
894 if (!obj->mainref) {
895 if (_rtld_objlist_find(&obj->dldags, root))
896 return;
897 dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
898 root->path));
899 _rtld_objlist_push_tail(&obj->dldags, root);
900 _rtld_objlist_push_tail(&root->dagmembers, obj);
901 }
902 for (needed = obj->needed; needed != NULL; needed = needed->next)
903 if (needed->obj != NULL)
904 _rtld_init_dag1(root, needed->obj);
905 }
906
907 /*
908 * Note, this is called only for objects loaded by dlopen().
909 */
910 static void
_rtld_unload_object(sigset_t * mask,Obj_Entry * root,bool do_fini_funcs)911 _rtld_unload_object(sigset_t *mask, Obj_Entry *root, bool do_fini_funcs)
912 {
913
914 _rtld_unref_dag(root);
915 if (root->refcount == 0) { /* We are finished with some objects. */
916 Obj_Entry *obj;
917 Obj_Entry **linkp;
918 Objlist_Entry *elm;
919
920 /* Finalize objects that are about to be unmapped. */
921 if (do_fini_funcs)
922 _rtld_call_fini_functions(mask, 0);
923
924 /* Remove the DAG from all objects' DAG lists. */
925 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
926 _rtld_objlist_remove(&elm->obj->dldags, root);
927
928 /* Remove the DAG from the RTLD_GLOBAL list. */
929 if (root->globalref) {
930 root->globalref = 0;
931 _rtld_objlist_remove(&_rtld_list_global, root);
932 }
933
934 /* Unmap all objects that are no longer referenced. */
935 linkp = &_rtld_objlist->next;
936 while ((obj = *linkp) != NULL) {
937 if (obj->refcount == 0) {
938 dbg(("unloading \"%s\"", obj->path));
939 if (obj->ehdr != MAP_FAILED)
940 munmap(obj->ehdr, _rtld_pagesz);
941 munmap(obj->mapbase, obj->mapsize);
942 _rtld_objlist_remove(&_rtld_list_global, obj);
943 _rtld_linkmap_delete(obj);
944 *linkp = obj->next;
945 _rtld_objcount--;
946 _rtld_obj_free(obj);
947 } else
948 linkp = &obj->next;
949 }
950 _rtld_objtail = linkp;
951 }
952 }
953
954 void
_rtld_ref_dag(Obj_Entry * root)955 _rtld_ref_dag(Obj_Entry *root)
956 {
957 const Needed_Entry *needed;
958
959 assert(root);
960
961 ++root->refcount;
962
963 dbg(("incremented reference on \"%s\" (%d)", root->path,
964 root->refcount));
965 for (needed = root->needed; needed != NULL;
966 needed = needed->next) {
967 if (needed->obj != NULL)
968 _rtld_ref_dag(needed->obj);
969 }
970 }
971
972 static void
_rtld_unref_dag(Obj_Entry * root)973 _rtld_unref_dag(Obj_Entry *root)
974 {
975
976 assert(root);
977 assert(root->refcount != 0);
978
979 --root->refcount;
980 dbg(("decremented reference on \"%s\" (%d)", root->path,
981 root->refcount));
982
983 if (root->refcount == 0) {
984 const Needed_Entry *needed;
985
986 for (needed = root->needed; needed != NULL;
987 needed = needed->next) {
988 if (needed->obj != NULL)
989 _rtld_unref_dag(needed->obj);
990 }
991 }
992 }
993
__strong_alias(__dlclose,dlclose)994 __strong_alias(__dlclose,dlclose)
995 int
996 dlclose(void *handle)
997 {
998 Obj_Entry *root;
999 sigset_t mask;
1000
1001 dbg(("dlclose of %p", handle));
1002
1003 _rtld_exclusive_enter(&mask);
1004
1005 root = _rtld_dlcheck(handle);
1006
1007 if (root == NULL) {
1008 _rtld_exclusive_exit(&mask);
1009 return -1;
1010 }
1011
1012 _rtld_debug.r_state = RT_DELETE;
1013 _rtld_debug_state();
1014
1015 --root->dl_refcount;
1016 _rtld_unload_object(&mask, root, true);
1017
1018 _rtld_debug.r_state = RT_CONSISTENT;
1019 _rtld_debug_state();
1020
1021 _rtld_exclusive_exit(&mask);
1022
1023 return 0;
1024 }
1025
__strong_alias(__dlerror,dlerror)1026 __strong_alias(__dlerror,dlerror)
1027 char *
1028 dlerror(void)
1029 {
1030 char *msg = error_message;
1031
1032 error_message = NULL;
1033 return msg;
1034 }
1035
__strong_alias(__dlopen,dlopen)1036 __strong_alias(__dlopen,dlopen)
1037 void *
1038 dlopen(const char *name, int mode)
1039 {
1040 Obj_Entry **old_obj_tail;
1041 Obj_Entry *obj = NULL;
1042 int flags = _RTLD_DLOPEN;
1043 bool nodelete;
1044 bool now;
1045 sigset_t mask;
1046 int result;
1047
1048 dbg(("dlopen of %s 0x%x", name, mode));
1049
1050 _rtld_exclusive_enter(&mask);
1051
1052 old_obj_tail = _rtld_objtail;
1053
1054 flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
1055 flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
1056
1057 nodelete = (mode & RTLD_NODELETE) ? true : false;
1058 now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
1059
1060 _rtld_debug.r_state = RT_ADD;
1061 _rtld_debug_state();
1062
1063 if (name == NULL) {
1064 obj = _rtld_objmain;
1065 obj->refcount++;
1066 } else
1067 obj = _rtld_load_library(name, _rtld_objmain, flags);
1068
1069
1070 if (obj != NULL) {
1071 ++obj->dl_refcount;
1072 if (*old_obj_tail != NULL) { /* We loaded something new. */
1073 assert(*old_obj_tail == obj);
1074
1075 result = _rtld_load_needed_objects(obj, flags);
1076 if (result != -1) {
1077 Objlist_Entry *entry;
1078 _rtld_init_dag(obj);
1079 SIMPLEQ_FOREACH(entry, &obj->dagmembers, link) {
1080 result = _rtld_verify_object_versions(entry->obj);
1081 if (result == -1)
1082 break;
1083 }
1084 }
1085 if (result == -1 || _rtld_relocate_objects(obj,
1086 (now || obj->z_now)) == -1) {
1087 _rtld_unload_object(&mask, obj, false);
1088 obj->dl_refcount--;
1089 obj = NULL;
1090 } else {
1091 _rtld_call_init_functions(&mask);
1092 }
1093 }
1094 if (obj != NULL) {
1095 if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
1096 dbg(("dlopen obj %s nodelete", obj->path));
1097 _rtld_ref_dag(obj);
1098 obj->z_nodelete = obj->ref_nodel = true;
1099 }
1100 }
1101 }
1102 _rtld_debug.r_state = RT_CONSISTENT;
1103 _rtld_debug_state();
1104
1105 dbg(("dlopen of %s 0x%x returned %p%s%s%s", name, mode, obj,
1106 obj ? "" : " (", obj ? "" : error_message, obj ? "" : ")"));
1107
1108 _rtld_exclusive_exit(&mask);
1109
1110 return obj;
1111 }
1112
1113 /*
1114 * Find a symbol in the main program.
1115 */
1116 void *
_rtld_objmain_sym(const char * name)1117 _rtld_objmain_sym(const char *name)
1118 {
1119 Elf_Hash hash;
1120 const Elf_Sym *def;
1121 const Obj_Entry *obj;
1122 DoneList donelist;
1123
1124 hash.sysv = _rtld_sysv_hash(name);
1125 hash.gnu = _rtld_gnu_hash(name);
1126 obj = _rtld_objmain;
1127 _rtld_donelist_init(&donelist);
1128
1129 def = _rtld_symlook_list(name, &hash, &_rtld_list_main, &obj, 0,
1130 NULL, &donelist);
1131
1132 if (def != NULL)
1133 return obj->relocbase + def->st_value;
1134 return NULL;
1135 }
1136
1137 #if defined(__powerpc__) && !defined(__clang__)
1138 static __noinline void *
hackish_return_address(void)1139 hackish_return_address(void)
1140 {
1141 #if __GNUC_PREREQ__(6,0)
1142 #pragma GCC diagnostic push
1143 #pragma GCC diagnostic ignored "-Wframe-address"
1144 #endif
1145 return __builtin_return_address(1);
1146 #if __GNUC_PREREQ__(6,0)
1147 #pragma GCC diagnostic pop
1148 #endif
1149 }
1150 #endif
1151
1152 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1153 #define lookup_mutex_enter() _rtld_exclusive_enter(&mask)
1154 #define lookup_mutex_exit() _rtld_exclusive_exit(&mask)
1155 #else
1156 #define lookup_mutex_enter() _rtld_shared_enter()
1157 #define lookup_mutex_exit() _rtld_shared_exit()
1158 #endif
1159
1160 static void *
do_dlsym(void * handle,const char * name,const Ver_Entry * ventry,void * retaddr)1161 do_dlsym(void *handle, const char *name, const Ver_Entry *ventry, void *retaddr)
1162 {
1163 const Obj_Entry *obj;
1164 Elf_Hash hash;
1165 const Elf_Sym *def;
1166 const Obj_Entry *defobj;
1167 DoneList donelist;
1168 const u_int flags = SYMLOOK_DLSYM | SYMLOOK_IN_PLT;
1169 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1170 sigset_t mask;
1171 #endif
1172
1173 lookup_mutex_enter();
1174
1175 hash.sysv = _rtld_sysv_hash(name);
1176 hash.gnu = _rtld_gnu_hash(name);
1177 def = NULL;
1178 defobj = NULL;
1179
1180 switch ((intptr_t)handle) {
1181 case (intptr_t)NULL:
1182 case (intptr_t)RTLD_NEXT:
1183 case (intptr_t)RTLD_DEFAULT:
1184 case (intptr_t)RTLD_SELF:
1185 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1186 _rtld_error("Cannot determine caller's shared object");
1187 lookup_mutex_exit();
1188 return NULL;
1189 }
1190
1191 switch ((intptr_t)handle) {
1192 case (intptr_t)NULL: /* Just the caller's shared object. */
1193 def = _rtld_symlook_obj(name, &hash, obj, flags, ventry);
1194 defobj = obj;
1195 break;
1196
1197 case (intptr_t)RTLD_NEXT: /* Objects after callers */
1198 obj = obj->next;
1199 /*FALLTHROUGH*/
1200
1201 case (intptr_t)RTLD_SELF: /* Caller included */
1202 for (; obj; obj = obj->next) {
1203 if ((def = _rtld_symlook_obj(name, &hash, obj,
1204 flags, ventry)) != NULL) {
1205 defobj = obj;
1206 break;
1207 }
1208 }
1209 /*
1210 * Search the dynamic linker itself, and possibly
1211 * resolve the symbol from there if it is not defined
1212 * already or weak. This is how the application links
1213 * to dynamic linker services such as dlopen.
1214 */
1215 if (!def || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1216 const Elf_Sym *symp = _rtld_symlook_obj(name,
1217 &hash, &_rtld_objself, flags, ventry);
1218 if (symp != NULL) {
1219 def = symp;
1220 defobj = &_rtld_objself;
1221 }
1222 }
1223 break;
1224
1225 case (intptr_t)RTLD_DEFAULT:
1226 def = _rtld_symlook_default(name, &hash, obj, &defobj,
1227 flags, ventry);
1228 break;
1229
1230 default:
1231 abort();
1232 }
1233 break;
1234
1235 default:
1236 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1237 lookup_mutex_exit();
1238 return NULL;
1239 }
1240
1241 _rtld_donelist_init(&donelist);
1242
1243 if (obj->mainprog) {
1244 /* Search main program and all libraries loaded by it */
1245 def = _rtld_symlook_list(name, &hash, &_rtld_list_main,
1246 &defobj, flags, ventry, &donelist);
1247 } else {
1248 Needed_Entry fake;
1249 DoneList depth;
1250
1251 /* Search the object and all the libraries loaded by it. */
1252 fake.next = NULL;
1253 fake.obj = __UNCONST(obj);
1254 fake.name = 0;
1255
1256 _rtld_donelist_init(&depth);
1257 def = _rtld_symlook_needed(name, &hash, &fake, &defobj,
1258 flags, ventry, &donelist, &depth);
1259 }
1260
1261 break;
1262 }
1263
1264 if (def != NULL) {
1265 void *p;
1266
1267 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
1268 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1269 lookup_mutex_exit();
1270 _rtld_shared_enter();
1271 #endif
1272 p = (void *)_rtld_resolve_ifunc(defobj, def);
1273 _rtld_shared_exit();
1274 return p;
1275 }
1276
1277 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1278 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) {
1279 p = (void *)_rtld_function_descriptor_alloc(defobj,
1280 def, 0);
1281 lookup_mutex_exit();
1282 return p;
1283 }
1284 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1285 p = defobj->relocbase + def->st_value;
1286 lookup_mutex_exit();
1287 return p;
1288 }
1289
1290 _rtld_error("Undefined symbol \"%s\"", name);
1291 lookup_mutex_exit();
1292 return NULL;
1293 }
1294
__strong_alias(__dlsym,dlsym)1295 __strong_alias(__dlsym,dlsym)
1296 void *
1297 dlsym(void *handle, const char *name)
1298 {
1299 void *retaddr;
1300
1301 dbg(("dlsym of %s in %p", name, handle));
1302
1303 #if defined(__powerpc__) && !defined(__clang__)
1304 retaddr = hackish_return_address();
1305 #else
1306 retaddr = __builtin_return_address(0);
1307 #endif
1308 return do_dlsym(handle, name, NULL, retaddr);
1309 }
1310
__strong_alias(__dlvsym,dlvsym)1311 __strong_alias(__dlvsym,dlvsym)
1312 void *
1313 dlvsym(void *handle, const char *name, const char *version)
1314 {
1315 Ver_Entry *ventry = NULL;
1316 Ver_Entry ver_entry;
1317 void *retaddr;
1318
1319 dbg(("dlvsym of %s@%s in %p", name, version ? version : NULL, handle));
1320
1321 if (version != NULL) {
1322 ver_entry.name = version;
1323 ver_entry.file = NULL;
1324 ver_entry.hash = _rtld_sysv_hash(version);
1325 ver_entry.flags = 0;
1326 ventry = &ver_entry;
1327 }
1328 #if defined(__powerpc__) && !defined(__clang__)
1329 retaddr = hackish_return_address();
1330 #else
1331 retaddr = __builtin_return_address(0);
1332 #endif
1333 return do_dlsym(handle, name, ventry, retaddr);
1334 }
1335
__strong_alias(__dladdr,dladdr)1336 __strong_alias(__dladdr,dladdr)
1337 int
1338 dladdr(const void *addr, Dl_info *info)
1339 {
1340 const Obj_Entry *obj;
1341 const Elf_Sym *def, *best_def;
1342 void *symbol_addr;
1343 unsigned long symoffset;
1344 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1345 sigset_t mask;
1346 #endif
1347
1348 dbg(("dladdr of %p", addr));
1349
1350 lookup_mutex_enter();
1351
1352 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1353 addr = _rtld_function_descriptor_function(addr);
1354 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1355
1356 obj = _rtld_obj_from_addr(addr);
1357 if (obj == NULL) {
1358 _rtld_error("No shared object contains address");
1359 lookup_mutex_exit();
1360 return 0;
1361 }
1362 info->dli_fname = obj->path;
1363 info->dli_fbase = obj->mapbase;
1364 info->dli_saddr = (void *)0;
1365 info->dli_sname = NULL;
1366
1367 /*
1368 * Walk the symbol list looking for the symbol whose address is
1369 * closest to the address sent in.
1370 */
1371 best_def = NULL;
1372 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1373 def = obj->symtab + symoffset;
1374
1375 /*
1376 * For skip the symbol if st_shndx is either SHN_UNDEF or
1377 * SHN_COMMON.
1378 */
1379 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1380 continue;
1381
1382 /*
1383 * If the symbol is greater than the specified address, or if it
1384 * is further away from addr than the current nearest symbol,
1385 * then reject it.
1386 */
1387 symbol_addr = obj->relocbase + def->st_value;
1388 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1389 continue;
1390
1391 /* Update our idea of the nearest symbol. */
1392 info->dli_sname = obj->strtab + def->st_name;
1393 info->dli_saddr = symbol_addr;
1394 best_def = def;
1395
1396
1397 /* Exact match? */
1398 if (info->dli_saddr == addr)
1399 break;
1400 }
1401
1402 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1403 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
1404 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
1405 best_def, 0);
1406 #else
1407 __USE(best_def);
1408 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1409
1410 lookup_mutex_exit();
1411 return 1;
1412 }
1413
__strong_alias(__dlinfo,dlinfo)1414 __strong_alias(__dlinfo,dlinfo)
1415 int
1416 dlinfo(void *handle, int req, void *v)
1417 {
1418 const Obj_Entry *obj;
1419 void *retaddr;
1420
1421 dbg(("dlinfo for %p %d", handle, req));
1422
1423 _rtld_shared_enter();
1424
1425 if (handle == RTLD_SELF) {
1426 #if defined(__powerpc__) && !defined(__clang__)
1427 retaddr = hackish_return_address();
1428 #else
1429 retaddr = __builtin_return_address(0);
1430 #endif
1431 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1432 _rtld_error("Cannot determine caller's shared object");
1433 _rtld_shared_exit();
1434 return -1;
1435 }
1436 } else {
1437 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1438 _rtld_shared_exit();
1439 return -1;
1440 }
1441 }
1442
1443 switch (req) {
1444 case RTLD_DI_LINKMAP:
1445 {
1446 const struct link_map **map = v;
1447
1448 *map = &obj->linkmap;
1449 break;
1450 }
1451
1452 default:
1453 _rtld_error("Invalid request");
1454 _rtld_shared_exit();
1455 return -1;
1456 }
1457
1458 _rtld_shared_exit();
1459 return 0;
1460 }
1461
1462 static void
_rtld_fill_dl_phdr_info(const Obj_Entry * obj,struct dl_phdr_info * phdr_info)1463 _rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
1464 {
1465
1466 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
1467 /* XXX: wrong but not fixing it yet */
1468 phdr_info->dlpi_name = obj->path;
1469 phdr_info->dlpi_phdr = obj->phdr;
1470 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
1471 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
1472 phdr_info->dlpi_tls_modid = obj->tlsindex;
1473 phdr_info->dlpi_tls_data = obj->tlsinit;
1474 #else
1475 phdr_info->dlpi_tls_modid = 0;
1476 phdr_info->dlpi_tls_data = 0;
1477 #endif
1478 phdr_info->dlpi_adds = _rtld_objloads;
1479 phdr_info->dlpi_subs = _rtld_objloads - _rtld_objcount;
1480 }
1481
1482 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
1483 int
dl_iterate_phdr(int (* callback)(struct dl_phdr_info *,size_t,void *),void * param)1484 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
1485 {
1486 struct dl_phdr_info phdr_info;
1487 const Obj_Entry *obj;
1488 int error = 0;
1489
1490 dbg(("dl_iterate_phdr"));
1491
1492 _rtld_shared_enter();
1493
1494 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1495 _rtld_fill_dl_phdr_info(obj, &phdr_info);
1496
1497 /* XXXlocking: exit point */
1498 error = callback(&phdr_info, sizeof(phdr_info), param);
1499 if (error)
1500 break;
1501 }
1502
1503 if (error == 0) {
1504 _rtld_fill_dl_phdr_info(&_rtld_objself, &phdr_info);
1505
1506 /* XXXlocking: exit point */
1507 error = callback(&phdr_info, sizeof(phdr_info), param);
1508 }
1509
1510 _rtld_shared_exit();
1511 return error;
1512 }
1513
1514 void
__dl_cxa_refcount(void * addr,ssize_t delta)1515 __dl_cxa_refcount(void *addr, ssize_t delta)
1516 {
1517 sigset_t mask;
1518 Obj_Entry *obj;
1519
1520 if (delta == 0)
1521 return;
1522
1523 dbg(("__dl_cxa_refcount of %p with %zd", addr, delta));
1524
1525 _rtld_exclusive_enter(&mask);
1526 obj = _rtld_obj_from_addr(addr);
1527
1528 if (obj == NULL) {
1529 dbg(("__dl_cxa_refcont: address not found"));
1530 _rtld_error("No shared object contains address");
1531 _rtld_exclusive_exit(&mask);
1532 return;
1533 }
1534 if (delta > 0 && obj->cxa_refcount > SIZE_MAX - delta)
1535 _rtld_error("Reference count overflow");
1536 else if (delta < 0 && obj->cxa_refcount < -1 + (size_t)-(delta + 1))
1537 _rtld_error("Reference count underflow");
1538 else {
1539 if (obj->cxa_refcount == 0)
1540 ++obj->refcount;
1541 obj->cxa_refcount += delta;
1542 dbg(("new reference count: %zu", obj->cxa_refcount));
1543 if (obj->cxa_refcount == 0) {
1544 --obj->refcount;
1545 if (obj->refcount == 0)
1546 _rtld_unload_object(&mask, obj, true);
1547 }
1548 }
1549
1550 _rtld_exclusive_exit(&mask);
1551 }
1552
1553 __dso_public pid_t
__locked_fork(int * my_errno)1554 __locked_fork(int *my_errno)
1555 {
1556 pid_t result;
1557
1558 _rtld_shared_enter();
1559 result = __fork();
1560 if (result == -1)
1561 *my_errno = errno;
1562 _rtld_shared_exit();
1563
1564 return result;
1565 }
1566
1567 /*
1568 * Error reporting function. Use it like printf. If formats the message
1569 * into a buffer, and sets things up so that the next call to dlerror()
1570 * will return the message.
1571 */
1572 void
_rtld_error(const char * fmt,...)1573 _rtld_error(const char *fmt,...)
1574 {
1575 static char buf[512];
1576 va_list ap;
1577
1578 va_start(ap, fmt);
1579 xvsnprintf(buf, sizeof buf, fmt, ap);
1580 dbg(("%s: %s", __func__, buf));
1581 error_message = buf;
1582 va_end(ap);
1583 }
1584
1585 void
_rtld_debug_state(void)1586 _rtld_debug_state(void)
1587 {
1588 #if defined(__hppa__)
1589 __asm volatile("nop" ::: "memory");
1590 #endif
1591
1592 /* Prevent optimizer from removing calls to this function */
1593 __insn_barrier();
1594 }
1595
1596 void
_rtld_linkmap_add(Obj_Entry * obj)1597 _rtld_linkmap_add(Obj_Entry *obj)
1598 {
1599 struct link_map *l = &obj->linkmap;
1600 struct link_map *prev;
1601
1602 obj->linkmap.l_name = obj->path;
1603 obj->linkmap.l_addr = obj->relocbase;
1604 obj->linkmap.l_ld = obj->dynamic;
1605 #ifdef __mips__
1606 /* XXX This field is not standard and will be removed eventually. */
1607 obj->linkmap.l_offs = obj->relocbase;
1608 #endif
1609
1610 if (_rtld_debug.r_map == NULL) {
1611 _rtld_debug.r_map = l;
1612 return;
1613 }
1614
1615 /*
1616 * Scan to the end of the list, but not past the entry for the
1617 * dynamic linker, which we want to keep at the very end.
1618 */
1619 for (prev = _rtld_debug.r_map;
1620 prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
1621 prev = prev->l_next);
1622
1623 l->l_prev = prev;
1624 l->l_next = prev->l_next;
1625 if (l->l_next != NULL)
1626 l->l_next->l_prev = l;
1627 prev->l_next = l;
1628 }
1629
1630 void
_rtld_linkmap_delete(Obj_Entry * obj)1631 _rtld_linkmap_delete(Obj_Entry *obj)
1632 {
1633 struct link_map *l = &obj->linkmap;
1634
1635 if (l->l_prev == NULL) {
1636 if ((_rtld_debug.r_map = l->l_next) != NULL)
1637 l->l_next->l_prev = NULL;
1638 return;
1639 }
1640 if ((l->l_prev->l_next = l->l_next) != NULL)
1641 l->l_next->l_prev = l->l_prev;
1642 }
1643
1644 static Obj_Entry *
_rtld_obj_from_addr(const void * addr)1645 _rtld_obj_from_addr(const void *addr)
1646 {
1647 Obj_Entry *obj;
1648
1649 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1650 if (addr < (void *) obj->mapbase)
1651 continue;
1652 if (addr < (void *) (obj->mapbase + obj->mapsize))
1653 return obj;
1654 }
1655 return NULL;
1656 }
1657
1658 static void
_rtld_objlist_clear(Objlist * list)1659 _rtld_objlist_clear(Objlist *list)
1660 {
1661 while (!SIMPLEQ_EMPTY(list)) {
1662 Objlist_Entry* elm = SIMPLEQ_FIRST(list);
1663 SIMPLEQ_REMOVE_HEAD(list, link);
1664 xfree(elm);
1665 }
1666 }
1667
1668 static void
_rtld_objlist_remove(Objlist * list,Obj_Entry * obj)1669 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
1670 {
1671 Objlist_Entry *elm;
1672
1673 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
1674 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1675 xfree(elm);
1676 }
1677 }
1678
1679 #define RTLD_EXCLUSIVE_MASK 0x80000000U
1680 static volatile unsigned int _rtld_mutex;
1681 static volatile unsigned int _rtld_waiter_exclusive;
1682 static volatile unsigned int _rtld_waiter_shared;
1683
1684 void
_rtld_shared_enter(void)1685 _rtld_shared_enter(void)
1686 {
1687 unsigned int cur;
1688 lwpid_t waiter, self = 0;
1689
1690 for (;;) {
1691 cur = _rtld_mutex;
1692 /*
1693 * First check if we are currently not exclusively locked.
1694 */
1695 if ((cur & RTLD_EXCLUSIVE_MASK) == 0) {
1696 /* Yes, so increment use counter */
1697 if (atomic_cas_uint(&_rtld_mutex, cur, cur + 1) != cur)
1698 continue;
1699 membar_acquire();
1700 return;
1701 }
1702 /*
1703 * Someone has an exclusive lock. Puts us on the waiter list.
1704 */
1705 if (!self)
1706 self = _lwp_self();
1707 if (cur == (self | RTLD_EXCLUSIVE_MASK)) {
1708 if (_rtld_mutex_may_recurse)
1709 return;
1710 _rtld_error("%s: dead lock detected", __func__);
1711 _rtld_die();
1712 }
1713 waiter = atomic_swap_uint(&_rtld_waiter_shared, self);
1714 /*
1715 * Check for race against _rtld_exclusive_exit before sleeping.
1716 */
1717 membar_sync();
1718 if ((_rtld_mutex & RTLD_EXCLUSIVE_MASK) ||
1719 _rtld_waiter_exclusive)
1720 _lwp_park(CLOCK_REALTIME, 0, NULL, 0,
1721 __UNVOLATILE(&_rtld_mutex), NULL);
1722 /* Try to remove us from the waiter list. */
1723 atomic_cas_uint(&_rtld_waiter_shared, self, 0);
1724 if (waiter)
1725 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1726 }
1727 }
1728
1729 void
_rtld_shared_exit(void)1730 _rtld_shared_exit(void)
1731 {
1732 lwpid_t waiter;
1733
1734 /*
1735 * Shared lock taken after an exclusive lock.
1736 * Just assume this is a partial recursion.
1737 */
1738 if (_rtld_mutex & RTLD_EXCLUSIVE_MASK)
1739 return;
1740
1741 /*
1742 * Wakeup LWPs waiting for an exclusive lock if this is the last
1743 * LWP on the shared lock.
1744 */
1745 membar_release();
1746 if (atomic_dec_uint_nv(&_rtld_mutex))
1747 return;
1748 membar_sync();
1749 if ((waiter = _rtld_waiter_exclusive) != 0)
1750 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1751 }
1752
1753 void
_rtld_exclusive_enter(sigset_t * mask)1754 _rtld_exclusive_enter(sigset_t *mask)
1755 {
1756 lwpid_t waiter, self = _lwp_self();
1757 unsigned int locked_value = (unsigned int)self | RTLD_EXCLUSIVE_MASK;
1758 unsigned int cur;
1759 sigset_t blockmask;
1760
1761 sigfillset(&blockmask);
1762 sigdelset(&blockmask, SIGTRAP); /* Allow the debugger */
1763 sigprocmask(SIG_BLOCK, &blockmask, mask);
1764
1765 for (;;) {
1766 if (atomic_cas_uint(&_rtld_mutex, 0, locked_value) == 0) {
1767 membar_acquire();
1768 break;
1769 }
1770 waiter = atomic_swap_uint(&_rtld_waiter_exclusive, self);
1771 membar_sync();
1772 cur = _rtld_mutex;
1773 if (cur == locked_value) {
1774 _rtld_error("%s: dead lock detected", __func__);
1775 _rtld_die();
1776 }
1777 if (cur)
1778 _lwp_park(CLOCK_REALTIME, 0, NULL, 0,
1779 __UNVOLATILE(&_rtld_mutex), NULL);
1780 atomic_cas_uint(&_rtld_waiter_exclusive, self, 0);
1781 if (waiter)
1782 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1783 }
1784 }
1785
1786 void
_rtld_exclusive_exit(sigset_t * mask)1787 _rtld_exclusive_exit(sigset_t *mask)
1788 {
1789 lwpid_t waiter;
1790
1791 membar_release();
1792 _rtld_mutex = 0;
1793 membar_sync();
1794 if ((waiter = _rtld_waiter_exclusive) != 0)
1795 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1796
1797 if ((waiter = _rtld_waiter_shared) != 0)
1798 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1799
1800 sigprocmask(SIG_SETMASK, mask, NULL);
1801 }
1802
1803 int
_rtld_relro(const Obj_Entry * obj,bool wantmain)1804 _rtld_relro(const Obj_Entry *obj, bool wantmain)
1805 {
1806 #ifdef GNU_RELRO
1807 /*
1808 * If our VM page size is larger than the page size used by the
1809 * linker when laying out the object, we could end up making data
1810 * read-only that is unintended. Detect and avoid this situation.
1811 * It may mean we are unable to protect everything we'd like, but
1812 * it's better than crashing.
1813 */
1814 uintptr_t relro_end = (uintptr_t)obj->relro_page + obj->relro_size;
1815 uintptr_t relro_start = round_down((uintptr_t)obj->relro_page);
1816 assert(relro_end >= relro_start);
1817 size_t relro_size = round_down(relro_end) - relro_start;
1818
1819 if (relro_size == 0)
1820 return 0;
1821 if (wantmain != (obj ==_rtld_objmain))
1822 return 0;
1823
1824 dbg(("RELRO %s %p %zx\n", obj->path, (void *)relro_start, relro_size));
1825 if (mprotect((void *)relro_start, relro_size, PROT_READ) == -1) {
1826 _rtld_error("%s: Cannot enforce relro " "protection: %s",
1827 obj->path, xstrerror(errno));
1828 return -1;
1829 }
1830 #endif
1831 return 0;
1832 }
1833