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