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