rtld.c revision 1.155 1 /* $NetBSD: rtld.c,v 1.155 2011/11/25 21:27:15 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.155 2011/11/25 21:27:15 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 Obj_Entry *obj;
377 Elf_Addr *const osp = sp;
378 bool bind_now = 0;
379 const char *ld_bind_now, *ld_preload, *ld_library_path;
380 const char **argv;
381 const char *execname;
382 long argc;
383 const char **real___progname;
384 const Obj_Entry **real___mainprog_obj;
385 char ***real_environ;
386 sigset_t mask;
387 #ifdef DEBUG
388 const char *ld_debug;
389 #endif
390 #ifdef RTLD_DEBUG
391 int i = 0;
392 #endif
393
394 /*
395 * On entry, the dynamic linker itself has not been relocated yet.
396 * Be very careful not to reference any global data until after
397 * _rtld_init has returned. It is OK to reference file-scope statics
398 * and string constants, and to call static and global functions.
399 */
400 /* Find the auxiliary vector on the stack. */
401 /* first Elf_Word reserved to address of exit routine */
402 #if defined(RTLD_DEBUG)
403 debug = 1;
404 dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
405 (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
406 #if 0
407 dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
408 &_DYNAMIC));
409 #endif
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 dbg(("checking for required versions"));
639 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
640 if (_rtld_verify_object_versions(obj) == -1)
641 _rtld_die();
642 }
643
644 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
645 dbg(("initializing initial Thread Local Storage offsets"));
646 /*
647 * All initial objects get the TLS space from the static block.
648 */
649 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
650 _rtld_tls_offset_allocate(obj);
651 #endif
652
653 dbg(("relocating objects"));
654 if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
655 _rtld_die();
656
657 dbg(("doing copy relocations"));
658 if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
659 _rtld_die();
660
661 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
662 dbg(("initializing Thread Local Storage for main thread"));
663 /*
664 * Set up TLS area for the main thread.
665 * This has to be done after all relocations are processed,
666 * since .tdata may contain relocations.
667 */
668 _rtld_tls_initial_allocation();
669 #endif
670
671 /*
672 * Set the __progname, environ and, __mainprog_obj before
673 * calling anything that might use them.
674 */
675 real___progname = _rtld_objmain_sym("__progname");
676 if (real___progname) {
677 if (argv[0] != NULL) {
678 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
679 (*real___progname) = argv[0];
680 else
681 (*real___progname)++;
682 } else {
683 (*real___progname) = NULL;
684 }
685 }
686 real_environ = _rtld_objmain_sym("environ");
687 if (real_environ)
688 *real_environ = environ;
689 /*
690 * Set __mainprog_obj for old binaries.
691 */
692 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
693 if (real___mainprog_obj)
694 *real___mainprog_obj = _rtld_objmain;
695
696 _rtld_exclusive_enter(&mask);
697
698 dbg(("calling _init functions"));
699 _rtld_call_init_functions(&mask);
700
701 dbg(("control at program entry point = %p, obj = %p, exit = %p",
702 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
703
704 _rtld_exclusive_exit(&mask);
705
706 /*
707 * Return with the entry point and the exit procedure in at the top
708 * of stack.
709 */
710
711 _rtld_debug_state(); /* say hello to gdb! */
712
713 ((void **) osp)[0] = _rtld_exit;
714 ((void **) osp)[1] = _rtld_objmain;
715 return (Elf_Addr) _rtld_objmain->entry;
716 }
717
718 void
719 _rtld_die(void)
720 {
721 const char *msg = dlerror();
722
723 if (msg == NULL)
724 msg = "Fatal error";
725 xerrx(1, "%s", msg);
726 }
727
728 static Obj_Entry *
729 _rtld_dlcheck(void *handle)
730 {
731 Obj_Entry *obj;
732
733 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
734 if (obj == (Obj_Entry *) handle)
735 break;
736
737 if (obj == NULL || obj->dl_refcount == 0) {
738 xwarnx("Invalid shared object handle %p", handle);
739 return NULL;
740 }
741 return obj;
742 }
743
744 static void
745 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
746 {
747 Needed_Entry* elm;
748
749 /* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
750
751 if (obj->init_done)
752 return;
753 obj->init_done = 1;
754
755 for (elm = obj->needed; elm != NULL; elm = elm->next) {
756 if (elm->obj != NULL) {
757 _rtld_initlist_visit(list, elm->obj, rev);
758 }
759 }
760
761 if (rev) {
762 _rtld_objlist_push_head(list, obj);
763 } else {
764 _rtld_objlist_push_tail(list, obj);
765 }
766 }
767
768 static void
769 _rtld_initlist_tsort(Objlist* list, int rev)
770 {
771 dbg(("_rtld_initlist_tsort"));
772
773 Obj_Entry* obj;
774
775 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
776 obj->init_done = 0;
777 }
778
779 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
780 _rtld_initlist_visit(list, obj, rev);
781 }
782 }
783
784 static void
785 _rtld_init_dag(Obj_Entry *root)
786 {
787
788 _rtld_init_dag1(root, root);
789 }
790
791 static void
792 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
793 {
794 const Needed_Entry *needed;
795
796 if (!obj->mainref) {
797 if (_rtld_objlist_find(&obj->dldags, root))
798 return;
799 dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
800 root->path));
801 _rtld_objlist_push_tail(&obj->dldags, root);
802 _rtld_objlist_push_tail(&root->dagmembers, obj);
803 }
804 for (needed = obj->needed; needed != NULL; needed = needed->next)
805 if (needed->obj != NULL)
806 _rtld_init_dag1(root, needed->obj);
807 }
808
809 /*
810 * Note, this is called only for objects loaded by dlopen().
811 */
812 static void
813 _rtld_unload_object(sigset_t *mask, Obj_Entry *root, bool do_fini_funcs)
814 {
815
816 _rtld_unref_dag(root);
817 if (root->refcount == 0) { /* We are finished with some objects. */
818 Obj_Entry *obj;
819 Obj_Entry **linkp;
820 Objlist_Entry *elm;
821
822 /* Finalize objects that are about to be unmapped. */
823 if (do_fini_funcs)
824 _rtld_call_fini_functions(mask, 0);
825
826 /* Remove the DAG from all objects' DAG lists. */
827 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
828 _rtld_objlist_remove(&elm->obj->dldags, root);
829
830 /* Remove the DAG from the RTLD_GLOBAL list. */
831 if (root->globalref) {
832 root->globalref = 0;
833 _rtld_objlist_remove(&_rtld_list_global, root);
834 }
835
836 /* Unmap all objects that are no longer referenced. */
837 linkp = &_rtld_objlist->next;
838 while ((obj = *linkp) != NULL) {
839 if (obj->refcount == 0) {
840 dbg(("unloading \"%s\"", obj->path));
841 if (obj->ehdr != MAP_FAILED)
842 munmap(obj->ehdr, _rtld_pagesz);
843 munmap(obj->mapbase, obj->mapsize);
844 _rtld_objlist_remove(&_rtld_list_global, obj);
845 _rtld_linkmap_delete(obj);
846 *linkp = obj->next;
847 _rtld_objcount--;
848 _rtld_obj_free(obj);
849 } else
850 linkp = &obj->next;
851 }
852 _rtld_objtail = linkp;
853 }
854 }
855
856 void
857 _rtld_ref_dag(Obj_Entry *root)
858 {
859 const Needed_Entry *needed;
860
861 assert(root);
862
863 ++root->refcount;
864
865 dbg(("incremented reference on \"%s\" (%d)", root->path,
866 root->refcount));
867 for (needed = root->needed; needed != NULL;
868 needed = needed->next) {
869 if (needed->obj != NULL)
870 _rtld_ref_dag(needed->obj);
871 }
872 }
873
874 static void
875 _rtld_unref_dag(Obj_Entry *root)
876 {
877
878 assert(root);
879 assert(root->refcount != 0);
880
881 --root->refcount;
882 dbg(("decremented reference on \"%s\" (%d)", root->path,
883 root->refcount));
884
885 if (root->refcount == 0) {
886 const Needed_Entry *needed;
887
888 for (needed = root->needed; needed != NULL;
889 needed = needed->next) {
890 if (needed->obj != NULL)
891 _rtld_unref_dag(needed->obj);
892 }
893 }
894 }
895
896 __strong_alias(__dlclose,dlclose)
897 int
898 dlclose(void *handle)
899 {
900 Obj_Entry *root;
901 sigset_t mask;
902
903 dbg(("dlclose of %p", handle));
904
905 _rtld_exclusive_enter(&mask);
906
907 root = _rtld_dlcheck(handle);
908
909 if (root == NULL) {
910 _rtld_exclusive_exit(&mask);
911 return -1;
912 }
913
914 _rtld_debug.r_state = RT_DELETE;
915 _rtld_debug_state();
916
917 --root->dl_refcount;
918 _rtld_unload_object(&mask, root, true);
919
920 _rtld_debug.r_state = RT_CONSISTENT;
921 _rtld_debug_state();
922
923 _rtld_exclusive_exit(&mask);
924
925 return 0;
926 }
927
928 __strong_alias(__dlerror,dlerror)
929 char *
930 dlerror(void)
931 {
932 char *msg = error_message;
933
934 error_message = NULL;
935 return msg;
936 }
937
938 __strong_alias(__dlopen,dlopen)
939 void *
940 dlopen(const char *name, int mode)
941 {
942 Obj_Entry **old_obj_tail = _rtld_objtail;
943 Obj_Entry *obj = NULL;
944 int flags = _RTLD_DLOPEN;
945 bool nodelete;
946 bool now;
947 sigset_t mask;
948 int result;
949
950 dbg(("dlopen of %s %d", name, mode));
951
952 _rtld_exclusive_enter(&mask);
953
954 flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
955 flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
956
957 nodelete = (mode & RTLD_NODELETE) ? true : false;
958 now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
959
960 _rtld_debug.r_state = RT_ADD;
961 _rtld_debug_state();
962
963 if (name == NULL) {
964 obj = _rtld_objmain;
965 obj->refcount++;
966 } else
967 obj = _rtld_load_library(name, _rtld_objmain, flags);
968
969
970 if (obj != NULL) {
971 ++obj->dl_refcount;
972 if (*old_obj_tail != NULL) { /* We loaded something new. */
973 assert(*old_obj_tail == obj);
974
975 result = _rtld_load_needed_objects(obj, flags);
976 if (result != -1) {
977 Objlist_Entry *entry;
978 _rtld_init_dag(obj);
979 SIMPLEQ_FOREACH(entry, &obj->dagmembers, link) {
980 result = _rtld_verify_object_versions(entry->obj);
981 if (result == -1)
982 break;
983 }
984 }
985 if (result == -1 || _rtld_relocate_objects(obj,
986 (now || obj->z_now)) == -1) {
987 _rtld_unload_object(&mask, obj, false);
988 obj->dl_refcount--;
989 obj = NULL;
990 } else {
991 _rtld_call_init_functions(&mask);
992 }
993 }
994 if (obj != NULL) {
995 if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
996 dbg(("dlopen obj %s nodelete", obj->path));
997 _rtld_ref_dag(obj);
998 obj->z_nodelete = obj->ref_nodel = true;
999 }
1000 }
1001 }
1002 _rtld_debug.r_state = RT_CONSISTENT;
1003 _rtld_debug_state();
1004
1005 _rtld_exclusive_exit(&mask);
1006
1007 return obj;
1008 }
1009
1010 /*
1011 * Find a symbol in the main program.
1012 */
1013 void *
1014 _rtld_objmain_sym(const char *name)
1015 {
1016 unsigned long hash;
1017 const Elf_Sym *def;
1018 const Obj_Entry *obj;
1019 DoneList donelist;
1020
1021 hash = _rtld_elf_hash(name);
1022 obj = _rtld_objmain;
1023 _rtld_donelist_init(&donelist);
1024
1025 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, 0,
1026 NULL, &donelist);
1027
1028 if (def != NULL)
1029 return obj->relocbase + def->st_value;
1030 return NULL;
1031 }
1032
1033 #ifdef __powerpc__
1034 static void *
1035 hackish_return_address(void)
1036 {
1037 return __builtin_return_address(1);
1038 }
1039 #endif
1040
1041 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1042 #define lookup_mutex_enter() _rtld_exclusive_enter(&mask)
1043 #define lookup_mutex_exit() _rtld_exclusive_exit(&mask)
1044 #else
1045 #define lookup_mutex_enter() _rtld_shared_enter()
1046 #define lookup_mutex_exit() _rtld_shared_exit()
1047 #endif
1048
1049 static void *
1050 do_dlsym(void *handle, const char *name, const Ver_Entry *ventry, void *retaddr)
1051 {
1052 const Obj_Entry *obj;
1053 unsigned long hash;
1054 const Elf_Sym *def;
1055 const Obj_Entry *defobj;
1056 DoneList donelist;
1057 const u_int flags = SYMLOOK_DLSYM | SYMLOOK_IN_PLT;
1058 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1059 sigset_t mask;
1060 #endif
1061
1062 lookup_mutex_enter();
1063
1064 hash = _rtld_elf_hash(name);
1065 def = NULL;
1066 defobj = NULL;
1067
1068 switch ((intptr_t)handle) {
1069 case (intptr_t)NULL:
1070 case (intptr_t)RTLD_NEXT:
1071 case (intptr_t)RTLD_DEFAULT:
1072 case (intptr_t)RTLD_SELF:
1073 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1074 _rtld_error("Cannot determine caller's shared object");
1075 lookup_mutex_exit();
1076 return NULL;
1077 }
1078
1079 switch ((intptr_t)handle) {
1080 case (intptr_t)NULL: /* Just the caller's shared object. */
1081 def = _rtld_symlook_obj(name, hash, obj, flags, ventry);
1082 defobj = obj;
1083 break;
1084
1085 case (intptr_t)RTLD_NEXT: /* Objects after callers */
1086 obj = obj->next;
1087 /*FALLTHROUGH*/
1088
1089 case (intptr_t)RTLD_SELF: /* Caller included */
1090 for (; obj; obj = obj->next) {
1091 if ((def = _rtld_symlook_obj(name, hash, obj,
1092 flags, ventry)) != NULL) {
1093 defobj = obj;
1094 break;
1095 }
1096 }
1097 break;
1098
1099 case (intptr_t)RTLD_DEFAULT:
1100 def = _rtld_symlook_default(name, hash, obj, &defobj,
1101 flags, ventry);
1102 break;
1103
1104 default:
1105 abort();
1106 }
1107 break;
1108
1109 default:
1110 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1111 lookup_mutex_exit();
1112 return NULL;
1113 }
1114
1115 _rtld_donelist_init(&donelist);
1116
1117 if (obj->mainprog) {
1118 /* Search main program and all libraries loaded by it */
1119 def = _rtld_symlook_list(name, hash, &_rtld_list_main,
1120 &defobj, flags, ventry, &donelist);
1121 } else {
1122 Needed_Entry fake;
1123 DoneList depth;
1124
1125 /* Search the object and all the libraries loaded by it. */
1126 fake.next = NULL;
1127 fake.obj = __UNCONST(obj);
1128 fake.name = 0;
1129
1130 _rtld_donelist_init(&depth);
1131 def = _rtld_symlook_needed(name, hash, &fake, &defobj,
1132 flags, ventry, &donelist, &depth);
1133 }
1134
1135 break;
1136 }
1137
1138 if (def != NULL) {
1139 void *p;
1140 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1141 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) {
1142 p = (void *)_rtld_function_descriptor_alloc(defobj,
1143 def, 0);
1144 lookup_mutex_exit();
1145 return p;
1146 }
1147 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1148 p = defobj->relocbase + def->st_value;
1149 lookup_mutex_exit();
1150 return p;
1151 }
1152
1153 _rtld_error("Undefined symbol \"%s\"", name);
1154 lookup_mutex_exit();
1155 return NULL;
1156 }
1157
1158 __strong_alias(__dlsym,dlsym)
1159 void *
1160 dlsym(void *handle, const char *name)
1161 {
1162 void *retaddr;
1163
1164 dbg(("dlsym of %s in %p", name, handle));
1165
1166 #ifdef __powerpc__
1167 retaddr = hackish_return_address();
1168 #else
1169 retaddr = __builtin_return_address(0);
1170 #endif
1171 return do_dlsym(handle, name, NULL, retaddr);
1172 }
1173
1174 __strong_alias(__dlvsym,dlvsym)
1175 void *
1176 dlvsym(void *handle, const char *name, const char *version)
1177 {
1178 Ver_Entry *ventry = NULL;
1179 Ver_Entry ver_entry;
1180 void *retaddr;
1181
1182 dbg(("dlvsym of %s@%s in %p", name, version ? version : NULL, handle));
1183
1184 if (version != NULL) {
1185 ver_entry.name = version;
1186 ver_entry.file = NULL;
1187 ver_entry.hash = _rtld_elf_hash(version);
1188 ver_entry.flags = 0;
1189 ventry = &ver_entry;
1190 }
1191 #ifdef __powerpc__
1192 retaddr = hackish_return_address();
1193 #else
1194 retaddr = __builtin_return_address(0);
1195 #endif
1196 return do_dlsym(handle, name, ventry, retaddr);
1197 }
1198
1199 __strong_alias(__dladdr,dladdr)
1200 int
1201 dladdr(const void *addr, Dl_info *info)
1202 {
1203 const Obj_Entry *obj;
1204 const Elf_Sym *def, *best_def;
1205 void *symbol_addr;
1206 unsigned long symoffset;
1207 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1208 sigset_t mask;
1209 #endif
1210
1211 dbg(("dladdr of %p", addr));
1212
1213 lookup_mutex_enter();
1214
1215 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1216 addr = _rtld_function_descriptor_function(addr);
1217 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1218
1219 obj = _rtld_obj_from_addr(addr);
1220 if (obj == NULL) {
1221 _rtld_error("No shared object contains address");
1222 lookup_mutex_enter();
1223 return 0;
1224 }
1225 info->dli_fname = obj->path;
1226 info->dli_fbase = obj->mapbase;
1227 info->dli_saddr = (void *)0;
1228 info->dli_sname = NULL;
1229
1230 /*
1231 * Walk the symbol list looking for the symbol whose address is
1232 * closest to the address sent in.
1233 */
1234 best_def = NULL;
1235 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1236 def = obj->symtab + symoffset;
1237
1238 /*
1239 * For skip the symbol if st_shndx is either SHN_UNDEF or
1240 * SHN_COMMON.
1241 */
1242 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1243 continue;
1244
1245 /*
1246 * If the symbol is greater than the specified address, or if it
1247 * is further away from addr than the current nearest symbol,
1248 * then reject it.
1249 */
1250 symbol_addr = obj->relocbase + def->st_value;
1251 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1252 continue;
1253
1254 /* Update our idea of the nearest symbol. */
1255 info->dli_sname = obj->strtab + def->st_name;
1256 info->dli_saddr = symbol_addr;
1257 best_def = def;
1258
1259 /* Exact match? */
1260 if (info->dli_saddr == addr)
1261 break;
1262 }
1263
1264 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1265 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
1266 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
1267 best_def, 0);
1268 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1269
1270 lookup_mutex_exit();
1271 return 1;
1272 }
1273
1274 __strong_alias(__dlinfo,dlinfo)
1275 int
1276 dlinfo(void *handle, int req, void *v)
1277 {
1278 const Obj_Entry *obj;
1279 void *retaddr;
1280
1281 dbg(("dlinfo for %p %d", handle, req));
1282
1283 _rtld_shared_enter();
1284
1285 if (handle == RTLD_SELF) {
1286 #ifdef __powerpc__
1287 retaddr = hackish_return_address();
1288 #else
1289 retaddr = __builtin_return_address(0);
1290 #endif
1291 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1292 _rtld_error("Cannot determine caller's shared object");
1293 _rtld_shared_exit();
1294 return -1;
1295 }
1296 } else {
1297 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1298 _rtld_error("Invalid handle");
1299 _rtld_shared_exit();
1300 return -1;
1301 }
1302 }
1303
1304 switch (req) {
1305 case RTLD_DI_LINKMAP:
1306 {
1307 const struct link_map **map = v;
1308
1309 *map = &obj->linkmap;
1310 break;
1311 }
1312
1313 default:
1314 _rtld_error("Invalid request");
1315 _rtld_shared_exit();
1316 return -1;
1317 }
1318
1319 _rtld_shared_exit();
1320 return 0;
1321 }
1322
1323 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
1324 int
1325 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
1326 {
1327 struct dl_phdr_info phdr_info;
1328 const Obj_Entry *obj;
1329 int error = 0;
1330
1331 dbg(("dl_iterate_phdr"));
1332
1333 _rtld_shared_enter();
1334
1335 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1336 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
1337 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
1338 STAILQ_FIRST(&obj->names)->name : obj->path;
1339 phdr_info.dlpi_phdr = obj->phdr;
1340 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
1341 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
1342 phdr_info.dlpi_tls_modid = obj->tlsindex;
1343 phdr_info.dlpi_tls_data = obj->tlsinit;
1344 #else
1345 phdr_info.dlpi_tls_modid = 0;
1346 phdr_info.dlpi_tls_data = 0;
1347 #endif
1348 phdr_info.dlpi_adds = _rtld_objloads;
1349 phdr_info.dlpi_subs = _rtld_objloads - _rtld_objcount;
1350
1351 /* XXXlocking: exit point */
1352 error = callback(&phdr_info, sizeof(phdr_info), param);
1353 if (error)
1354 break;
1355 }
1356
1357 _rtld_shared_exit();
1358 return error;
1359 }
1360
1361 /*
1362 * Error reporting function. Use it like printf. If formats the message
1363 * into a buffer, and sets things up so that the next call to dlerror()
1364 * will return the message.
1365 */
1366 void
1367 _rtld_error(const char *fmt,...)
1368 {
1369 static char buf[512];
1370 va_list ap;
1371
1372 va_start(ap, fmt);
1373 xvsnprintf(buf, sizeof buf, fmt, ap);
1374 error_message = buf;
1375 va_end(ap);
1376 }
1377
1378 void
1379 _rtld_debug_state(void)
1380 {
1381
1382 /* do nothing */
1383 }
1384
1385 void
1386 _rtld_linkmap_add(Obj_Entry *obj)
1387 {
1388 struct link_map *l = &obj->linkmap;
1389 struct link_map *prev;
1390
1391 obj->linkmap.l_name = obj->path;
1392 obj->linkmap.l_addr = obj->relocbase;
1393 obj->linkmap.l_ld = obj->dynamic;
1394 #ifdef __mips__
1395 /* XXX This field is not standard and will be removed eventually. */
1396 obj->linkmap.l_offs = obj->relocbase;
1397 #endif
1398
1399 if (_rtld_debug.r_map == NULL) {
1400 _rtld_debug.r_map = l;
1401 return;
1402 }
1403
1404 /*
1405 * Scan to the end of the list, but not past the entry for the
1406 * dynamic linker, which we want to keep at the very end.
1407 */
1408 for (prev = _rtld_debug.r_map;
1409 prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
1410 prev = prev->l_next);
1411
1412 l->l_prev = prev;
1413 l->l_next = prev->l_next;
1414 if (l->l_next != NULL)
1415 l->l_next->l_prev = l;
1416 prev->l_next = l;
1417 }
1418
1419 void
1420 _rtld_linkmap_delete(Obj_Entry *obj)
1421 {
1422 struct link_map *l = &obj->linkmap;
1423
1424 if (l->l_prev == NULL) {
1425 if ((_rtld_debug.r_map = l->l_next) != NULL)
1426 l->l_next->l_prev = NULL;
1427 return;
1428 }
1429 if ((l->l_prev->l_next = l->l_next) != NULL)
1430 l->l_next->l_prev = l->l_prev;
1431 }
1432
1433 static Obj_Entry *
1434 _rtld_obj_from_addr(const void *addr)
1435 {
1436 Obj_Entry *obj;
1437
1438 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1439 if (addr < (void *) obj->mapbase)
1440 continue;
1441 if (addr < (void *) (obj->mapbase + obj->mapsize))
1442 return obj;
1443 }
1444 return NULL;
1445 }
1446
1447 static void
1448 _rtld_objlist_clear(Objlist *list)
1449 {
1450 while (!SIMPLEQ_EMPTY(list)) {
1451 Objlist_Entry* elm = SIMPLEQ_FIRST(list);
1452 SIMPLEQ_REMOVE_HEAD(list, link);
1453 xfree(elm);
1454 }
1455 }
1456
1457 static void
1458 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
1459 {
1460 Objlist_Entry *elm;
1461
1462 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
1463 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1464 xfree(elm);
1465 }
1466 }
1467
1468 #define RTLD_EXCLUSIVE_MASK 0x80000000U
1469 static volatile unsigned int _rtld_mutex;
1470 static volatile unsigned int _rtld_waiter_exclusive;
1471 static volatile unsigned int _rtld_waiter_shared;
1472
1473 void
1474 _rtld_shared_enter(void)
1475 {
1476 unsigned int cur;
1477 lwpid_t waiter, self = 0;
1478
1479 membar_enter();
1480
1481 for (;;) {
1482 cur = _rtld_mutex;
1483 /*
1484 * First check if we are currently not exclusively locked.
1485 */
1486 if ((cur & RTLD_EXCLUSIVE_MASK) == 0) {
1487 /* Yes, so increment use counter */
1488 if (atomic_cas_uint(&_rtld_mutex, cur, cur + 1) != cur)
1489 continue;
1490 return;
1491 }
1492 /*
1493 * Someone has an exclusive lock. Puts us on the waiter list.
1494 */
1495 if (!self)
1496 self = _lwp_self();
1497 if (cur == (self | RTLD_EXCLUSIVE_MASK)) {
1498 if (_rtld_mutex_may_recurse)
1499 return;
1500 _rtld_error("dead lock detected");
1501 _rtld_die();
1502 }
1503 waiter = atomic_swap_uint(&_rtld_waiter_shared, self);
1504 /*
1505 * Check for race against _rtld_exclusive_exit before sleeping.
1506 */
1507 if ((_rtld_mutex & RTLD_EXCLUSIVE_MASK) ||
1508 _rtld_waiter_exclusive)
1509 _lwp_park(NULL, -1, __UNVOLATILE(&_rtld_mutex), NULL);
1510 /* Try to remove us from the waiter list. */
1511 atomic_cas_uint(&_rtld_waiter_shared, self, 0);
1512 if (waiter)
1513 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1514 }
1515 }
1516
1517 void
1518 _rtld_shared_exit(void)
1519 {
1520 lwpid_t waiter;
1521
1522 /*
1523 * Shared lock taken after an exclusive lock.
1524 * Just assume this is a partial recursion.
1525 */
1526 if (_rtld_mutex & RTLD_EXCLUSIVE_MASK)
1527 return;
1528
1529 /*
1530 * Wakeup LWPs waiting for an exclusive lock if this is the last
1531 * LWP on the shared lock.
1532 */
1533 if (atomic_dec_uint_nv(&_rtld_mutex))
1534 return;
1535 if ((waiter = _rtld_waiter_exclusive) != 0)
1536 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1537
1538 membar_exit();
1539 }
1540
1541 void
1542 _rtld_exclusive_enter(sigset_t *mask)
1543 {
1544 lwpid_t waiter, self = _lwp_self();
1545 unsigned int locked_value = (unsigned int)self | RTLD_EXCLUSIVE_MASK;
1546 unsigned int cur;
1547 sigset_t blockmask;
1548
1549 sigfillset(&blockmask);
1550 sigdelset(&blockmask, SIGTRAP); /* Allow the debugger */
1551 sigprocmask(SIG_BLOCK, &blockmask, mask);
1552
1553 membar_enter();
1554
1555 for (;;) {
1556 if (atomic_cas_uint(&_rtld_mutex, 0, locked_value) == 0)
1557 break;
1558 waiter = atomic_swap_uint(&_rtld_waiter_exclusive, self);
1559 cur = _rtld_mutex;
1560 if (cur == locked_value) {
1561 _rtld_error("dead lock detected");
1562 _rtld_die();
1563 }
1564 if (cur)
1565 _lwp_park(NULL, -1, __UNVOLATILE(&_rtld_mutex), NULL);
1566 atomic_cas_uint(&_rtld_waiter_exclusive, self, 0);
1567 if (waiter)
1568 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1569 }
1570 }
1571
1572 void
1573 _rtld_exclusive_exit(sigset_t *mask)
1574 {
1575 lwpid_t waiter;
1576
1577 _rtld_mutex = 0;
1578 if ((waiter = _rtld_waiter_exclusive) != 0)
1579 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1580
1581 if ((waiter = _rtld_waiter_shared) != 0)
1582 _lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
1583
1584 membar_exit();
1585 sigprocmask(SIG_SETMASK, mask, NULL);
1586 }
1587