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