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