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