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