Move primary cache code to libminixfs.
[minix.git] / libexec / ld.elf_so / rtld.c
blobb1a5462fbb76812019fd56cf8ee38d1711ff7ba2
1 /* $NetBSD: rtld.c,v 1.137 2010/12/24 12:41:43 skrll Exp $ */
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt@3am-software.com>
6 * Copyright 2002 Charles M. Hannum <root@ihack.net>
7 * All rights reserved.
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.
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.
36 * Dynamic linker for ELF.
38 * John Polstra <jdp@polstra.com>.
41 #ifdef __minix
42 #define munmap minix_munmap
43 #endif
45 #include <sys/cdefs.h>
46 #ifndef lint
47 __RCSID("$NetBSD: rtld.c,v 1.137 2010/12/24 12:41:43 skrll Exp $");
48 #endif /* not lint */
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdarg.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <sys/param.h>
59 #include <sys/mman.h>
60 #include <dirent.h>
62 #include <ctype.h>
64 #include <dlfcn.h>
65 #include "debug.h"
66 #include "rtld.h"
68 #if !defined(lint)
69 #include "sysident.h"
70 #endif
73 * Function declarations.
75 static void _rtld_init(caddr_t, caddr_t, const char *);
76 static void _rtld_exit(void);
78 Elf_Addr _rtld(Elf_Addr *, Elf_Addr);
82 * Data declarations.
84 static char *error_message; /* Message for dlopen(), or NULL */
86 struct r_debug _rtld_debug; /* for GDB; */
87 bool _rtld_trust; /* False for setuid and setgid programs */
88 Obj_Entry *_rtld_objlist; /* Head of linked list of shared objects */
89 Obj_Entry **_rtld_objtail; /* Link field of last object in list */
90 Obj_Entry *_rtld_objmain; /* The main program shared object */
91 Obj_Entry _rtld_objself; /* The dynamic linker shared object */
92 u_int _rtld_objcount; /* Number of objects in _rtld_objlist */
93 u_int _rtld_objloads; /* Number of objects loaded in _rtld_objlist */
94 const char _rtld_path[] = _PATH_RTLD;
96 /* Initialize a fake symbol for resolving undefined weak references. */
97 Elf_Sym _rtld_sym_zero = {
98 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
99 .st_shndx = SHN_ABS,
101 size_t _rtld_pagesz; /* Page size, as provided by kernel */
103 Search_Path *_rtld_default_paths;
104 Search_Path *_rtld_paths;
106 Library_Xform *_rtld_xforms;
109 * Global declarations normally provided by crt0.
111 char *__progname;
112 char **environ;
114 #if defined(RTLD_DEBUG)
115 #ifndef __sh__
116 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
117 #else /* 32-bit SuperH */
118 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
119 #endif
120 #endif /* RTLD_DEBUG */
121 extern Elf_Dyn _DYNAMIC;
123 static void _rtld_call_fini_functions(int);
124 static void _rtld_call_init_functions(void);
125 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
126 static void _rtld_initlist_tsort(Objlist *, int);
127 static Obj_Entry *_rtld_dlcheck(void *);
128 static void _rtld_init_dag(Obj_Entry *);
129 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
130 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
131 static void _rtld_objlist_clear(Objlist *);
132 static void _rtld_unload_object(Obj_Entry *, bool);
133 static void _rtld_unref_dag(Obj_Entry *);
134 static Obj_Entry *_rtld_obj_from_addr(const void *);
136 static void
137 _rtld_call_fini_functions(int force)
139 Objlist_Entry *elm;
140 Objlist finilist;
141 Obj_Entry *obj;
143 dbg(("_rtld_call_fini_functions(%d)", force));
145 SIMPLEQ_INIT(&finilist);
146 _rtld_initlist_tsort(&finilist, 1);
148 /* First pass: objects _not_ marked with DF_1_INITFIRST. */
149 SIMPLEQ_FOREACH(elm, &finilist, link) {
150 obj = elm->obj;
151 if (obj->refcount > 0 && !force) {
152 continue;
154 if (obj->fini == NULL || obj->fini_called || obj->z_initfirst) {
155 continue;
157 dbg (("calling fini function %s at %p", obj->path,
158 (void *)obj->fini));
159 obj->fini_called = 1;
160 (*obj->fini)();
163 /* Second pass: objects marked with DF_1_INITFIRST. */
164 SIMPLEQ_FOREACH(elm, &finilist, link) {
165 obj = elm->obj;
166 if (obj->refcount > 0 && !force) {
167 continue;
169 if (obj->fini == NULL || obj->fini_called) {
170 continue;
172 dbg (("calling fini function %s at %p (DF_1_INITFIRST)",
173 obj->path, (void *)obj->fini));
174 obj->fini_called = 1;
175 (*obj->fini)();
178 _rtld_objlist_clear(&finilist);
181 static void
182 _rtld_call_init_functions()
184 Objlist_Entry *elm;
185 Objlist initlist;
186 Obj_Entry *obj;
188 dbg(("_rtld_call_init_functions()"));
189 SIMPLEQ_INIT(&initlist);
190 _rtld_initlist_tsort(&initlist, 0);
192 /* First pass: objects marked with DF_1_INITFIRST. */
193 SIMPLEQ_FOREACH(elm, &initlist, link) {
194 obj = elm->obj;
195 if (obj->init == NULL || obj->init_called || !obj->z_initfirst) {
196 continue;
198 dbg (("calling init function %s at %p (DF_1_INITFIRST)",
199 obj->path, (void *)obj->init));
200 obj->init_called = 1;
201 (*obj->init)();
204 /* Second pass: all other objects. */
205 SIMPLEQ_FOREACH(elm, &initlist, link) {
206 obj = elm->obj;
207 if (obj->init == NULL || obj->init_called) {
208 continue;
210 dbg (("calling init function %s at %p", obj->path,
211 (void *)obj->init));
212 obj->init_called = 1;
213 (*obj->init)();
216 _rtld_objlist_clear(&initlist);
220 * Initialize the dynamic linker. The argument is the address at which
221 * the dynamic linker has been mapped into memory. The primary task of
222 * this function is to create an Obj_Entry for the dynamic linker and
223 * to resolve the PLT relocation for platforms that need it (those that
224 * define __HAVE_FUNCTION_DESCRIPTORS
226 static void
227 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
230 /* Conjure up an Obj_Entry structure for the dynamic linker. */
231 _rtld_objself.path = __UNCONST(_rtld_path);
232 _rtld_objself.pathlen = sizeof(_rtld_path)-1;
233 _rtld_objself.rtld = true;
234 _rtld_objself.mapbase = mapbase;
235 _rtld_objself.relocbase = relocbase;
236 _rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
237 _rtld_objself.strtab = "_rtld_sym_zero";
240 * Set value to -relocbase so that
242 * _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
244 * This allows unresolved references to weak symbols to be computed
245 * to a value of 0.
247 _rtld_sym_zero.st_value = -(uintptr_t)relocbase;
249 _rtld_digest_dynamic(_rtld_path, &_rtld_objself);
250 assert(!_rtld_objself.needed);
251 #if !defined(__hppa__)
252 assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
253 #else
254 _rtld_relocate_plt_objects(&_rtld_objself);
255 #endif
256 #if !defined(__mips__) && !defined(__hppa__)
257 assert(!_rtld_objself.pltgot);
258 #endif
259 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
260 /* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
261 assert(!_rtld_objself.textrel);
262 #endif
264 _rtld_add_paths(execname, &_rtld_default_paths,
265 RTLD_DEFAULT_LIBRARY_PATH);
267 #ifdef RTLD_ARCH_SUBDIR
268 _rtld_add_paths(execname, &_rtld_default_paths,
269 RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
270 #endif
273 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
275 _rtld_objlist = &_rtld_objself;
277 /* Make the object list empty again. */
278 _rtld_objlist = NULL;
279 _rtld_objtail = &_rtld_objlist;
280 _rtld_objcount = 0;
282 _rtld_debug.r_brk = _rtld_debug_state;
283 _rtld_debug.r_state = RT_CONSISTENT;
287 * Cleanup procedure. It will be called (by the atexit() mechanism) just
288 * before the process exits.
290 static void
291 _rtld_exit(void)
293 dbg(("rtld_exit()"));
295 _rtld_call_fini_functions(1);
299 * Main entry point for dynamic linking. The argument is the stack
300 * pointer. The stack is expected to be laid out as described in the
301 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
302 * the stack pointer points to a word containing ARGC. Following that
303 * in the stack is a null-terminated sequence of pointers to argument
304 * strings. Then comes a null-terminated sequence of pointers to
305 * environment strings. Finally, there is a sequence of "auxiliary
306 * vector" entries.
308 * This function returns the entry point for the main program, the dynamic
309 * linker's exit procedure in sp[0], and a pointer to the main object in
310 * sp[1].
312 Elf_Addr
313 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
315 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
316 *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
317 *pAUX_ruid, *pAUX_rgid;
318 const AuxInfo *pAUX_pagesz;
319 char **env, **oenvp;
320 const AuxInfo *aux;
321 const AuxInfo *auxp;
322 Elf_Addr *const osp = sp;
323 bool bind_now = 0;
324 const char *ld_bind_now, *ld_preload, *ld_library_path;
325 const char **argv;
326 const char *execname;
327 long argc;
328 const char **real___progname;
329 const Obj_Entry **real___mainprog_obj;
330 char ***real_environ;
331 #ifdef DEBUG
332 int i = 0;
333 const char *ld_debug;
334 #endif
337 * On entry, the dynamic linker itself has not been relocated yet.
338 * Be very careful not to reference any global data until after
339 * _rtld_init has returned. It is OK to reference file-scope statics
340 * and string constants, and to call static and global functions.
342 /* Find the auxiliary vector on the stack. */
343 /* first Elf_Word reserved to address of exit routine */
344 #if defined(RTLD_DEBUG)
345 debug = 1;
346 dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
347 (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
348 dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
349 &_DYNAMIC));
350 dbg(("_ctype_ is %p", _ctype_));
351 #endif
353 sp += 2; /* skip over return argument space */
354 argv = (const char **) &sp[1];
355 argc = *(long *)sp;
356 sp += 2 + argc; /* Skip over argc, arguments, and NULL
357 * terminator */
358 env = (char **) sp;
359 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
360 #if defined(RTLD_DEBUG)
361 dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
362 #endif
364 aux = (const AuxInfo *) sp;
366 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
367 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
368 pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
369 pAUX_pagesz = NULL;
371 execname = NULL;
373 /* Digest the auxiliary vector. */
374 for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
375 switch (auxp->a_type) {
376 case AT_BASE:
377 pAUX_base = auxp;
378 break;
379 case AT_ENTRY:
380 pAUX_entry = auxp;
381 break;
382 case AT_EXECFD:
383 pAUX_execfd = auxp;
384 break;
385 case AT_PHDR:
386 pAUX_phdr = auxp;
387 break;
388 case AT_PHENT:
389 pAUX_phent = auxp;
390 break;
391 case AT_PHNUM:
392 pAUX_phnum = auxp;
393 break;
394 #ifdef AT_EUID
395 case AT_EUID:
396 pAUX_euid = auxp;
397 break;
398 case AT_RUID:
399 pAUX_ruid = auxp;
400 break;
401 case AT_EGID:
402 pAUX_egid = auxp;
403 break;
404 case AT_RGID:
405 pAUX_rgid = auxp;
406 break;
407 #endif
408 #ifdef AT_SUN_EXECNAME
409 case AT_SUN_EXECNAME:
410 execname = (const char *)(const void *)auxp->a_v;
411 break;
412 #endif
413 case AT_PAGESZ:
414 pAUX_pagesz = auxp;
415 break;
419 /* Initialize and relocate ourselves. */
420 if (pAUX_base == NULL) {
421 _rtld_error("Bad pAUX_base");
422 _rtld_die();
424 assert(pAUX_pagesz != NULL);
425 _rtld_pagesz = (int)pAUX_pagesz->a_v;
426 _rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
428 __progname = _rtld_objself.path;
429 environ = env;
431 _rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
432 (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
433 ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
434 (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
436 #ifdef DEBUG
437 ld_debug = NULL;
438 #endif
439 ld_bind_now = NULL;
440 ld_library_path = NULL;
441 ld_preload = NULL;
443 * Inline avoid using normal getenv/unsetenv here as the libc
444 * code is quite a bit more complicated.
446 for (oenvp = env; *env != NULL; ++env) {
447 static const char bind_var[] = "LD_BIND_NOW=";
448 static const char debug_var[] = "LD_DEBUG=";
449 static const char path_var[] = "LD_LIBRARY_PATH=";
450 static const char preload_var[] = "LD_PRELOAD=";
451 #define LEN(x) (sizeof(x) - 1)
453 if ((*env)[0] != 'L' || (*env)[1] != 'D') {
455 * Special case to skip most entries without
456 * the more expensive calls to strncmp.
458 *oenvp++ = *env;
459 } else if (strncmp(*env, debug_var, LEN(debug_var)) == 0) {
460 if (_rtld_trust) {
461 #ifdef DEBUG
462 ld_debug = *env + LEN(debug_var);
463 #endif
464 *oenvp++ = *env;
466 } else if (strncmp(*env, bind_var, LEN(bind_var)) == 0) {
467 ld_bind_now = *env + LEN(bind_var);
468 } else if (strncmp(*env, path_var, LEN(path_var)) == 0) {
469 if (_rtld_trust) {
470 ld_library_path = *env + LEN(path_var);
471 *oenvp++ = *env;
473 } else if (strncmp(*env, preload_var, LEN(preload_var)) == 0) {
474 if (_rtld_trust) {
475 ld_preload = *env + LEN(preload_var);
476 *oenvp++ = *env;
478 } else {
479 *oenvp++ = *env;
481 #undef LEN
483 *oenvp++ = NULL;
485 if (ld_bind_now != NULL && *ld_bind_now != '\0')
486 bind_now = true;
487 if (_rtld_trust) {
488 #ifdef DEBUG
489 #ifdef RTLD_DEBUG
490 debug = 0;
491 #endif
492 if (ld_debug != NULL && *ld_debug != '\0')
493 debug = 1;
494 #endif
495 _rtld_add_paths(execname, &_rtld_paths, ld_library_path);
496 } else {
497 execname = NULL;
499 _rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
500 _PATH_LD_HINTS);
501 dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
502 _rtld_objself.mapbase, _rtld_objself.relocbase));
505 * Load the main program, or process its program header if it is
506 * already loaded.
508 if (pAUX_execfd != NULL) { /* Load the main program. */
509 int fd = pAUX_execfd->a_v;
510 const char *obj_name = argv[0] ? argv[0] : "main program";
511 dbg(("loading main program"));
512 _rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
513 close(fd);
514 if (_rtld_objmain == NULL)
515 _rtld_die();
516 } else { /* Main program already loaded. */
517 const Elf_Phdr *phdr;
518 int phnum;
519 caddr_t entry;
521 dbg(("processing main program's program header"));
522 assert(pAUX_phdr != NULL);
523 phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
524 assert(pAUX_phnum != NULL);
525 phnum = pAUX_phnum->a_v;
526 assert(pAUX_phent != NULL);
527 assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
528 assert(pAUX_entry != NULL);
529 entry = (caddr_t) pAUX_entry->a_v;
530 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
531 _rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
532 "main program");
533 _rtld_objmain->pathlen = strlen(_rtld_objmain->path);
536 _rtld_objmain->mainprog = true;
539 * Get the actual dynamic linker pathname from the executable if
540 * possible. (It should always be possible.) That ensures that
541 * gdb will find the right dynamic linker even if a non-standard
542 * one is being used.
544 if (_rtld_objmain->interp != NULL &&
545 strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
546 _rtld_objself.path = xstrdup(_rtld_objmain->interp);
547 dbg(("actual dynamic linker is %s", _rtld_objself.path));
549 _rtld_digest_dynamic(execname, _rtld_objmain);
551 /* Link the main program into the list of objects. */
552 *_rtld_objtail = _rtld_objmain;
553 _rtld_objtail = &_rtld_objmain->next;
554 _rtld_objcount++;
555 _rtld_objloads++;
557 _rtld_linkmap_add(_rtld_objmain);
558 _rtld_linkmap_add(&_rtld_objself);
560 ++_rtld_objmain->refcount;
561 _rtld_objmain->mainref = 1;
562 _rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
564 if (ld_preload) {
566 * Pre-load user-specified objects after the main program
567 * but before any shared object dependencies.
569 dbg(("preloading objects"));
570 if (_rtld_preload(ld_preload) == -1)
571 _rtld_die();
574 dbg(("loading needed objects"));
575 if (_rtld_load_needed_objects(_rtld_objmain, _RTLD_MAIN) == -1)
576 _rtld_die();
578 dbg(("relocating objects"));
579 if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
580 _rtld_die();
582 dbg(("doing copy relocations"));
583 if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
584 _rtld_die();
587 * Set the __progname, environ and, __mainprog_obj before
588 * calling anything that might use them.
590 real___progname = _rtld_objmain_sym("__progname");
591 if (real___progname) {
592 if (argv[0] != NULL) {
593 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
594 (*real___progname) = argv[0];
595 else
596 (*real___progname)++;
597 } else {
598 (*real___progname) = NULL;
601 real_environ = _rtld_objmain_sym("environ");
602 if (real_environ)
603 *real_environ = environ;
605 * Set __mainprog_obj for old binaries.
607 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
608 if (real___mainprog_obj)
609 *real___mainprog_obj = _rtld_objmain;
611 dbg(("calling _init functions"));
612 _rtld_call_init_functions();
614 dbg(("control at program entry point = %p, obj = %p, exit = %p",
615 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
618 * Return with the entry point and the exit procedure in at the top
619 * of stack.
622 _rtld_debug_state(); /* say hello to gdb! */
624 ((void **) osp)[0] = _rtld_exit;
625 ((void **) osp)[1] = _rtld_objmain;
626 return (Elf_Addr) _rtld_objmain->entry;
629 void
630 _rtld_die(void)
632 const char *msg = dlerror();
634 if (msg == NULL)
635 msg = "Fatal error";
636 xerrx(1, "%s", msg);
639 static Obj_Entry *
640 _rtld_dlcheck(void *handle)
642 Obj_Entry *obj;
644 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
645 if (obj == (Obj_Entry *) handle)
646 break;
648 if (obj == NULL || obj->dl_refcount == 0) {
649 xwarnx("Invalid shared object handle %p", handle);
650 return NULL;
652 return obj;
655 static void
656 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
658 Needed_Entry* elm;
660 /* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
662 if (obj->init_done)
663 return;
664 obj->init_done = 1;
666 for (elm = obj->needed; elm != NULL; elm = elm->next) {
667 if (elm->obj != NULL) {
668 _rtld_initlist_visit(list, elm->obj, rev);
672 if (rev) {
673 _rtld_objlist_push_head(list, obj);
674 } else {
675 _rtld_objlist_push_tail(list, obj);
679 static void
680 _rtld_initlist_tsort(Objlist* list, int rev)
682 dbg(("_rtld_initlist_tsort"));
684 Obj_Entry* obj;
686 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
687 obj->init_done = 0;
690 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
691 _rtld_initlist_visit(list, obj, rev);
695 static void
696 _rtld_init_dag(Obj_Entry *root)
699 _rtld_init_dag1(root, root);
702 static void
703 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
705 const Needed_Entry *needed;
707 if (!obj->mainref) {
708 if (_rtld_objlist_find(&obj->dldags, root))
709 return;
710 dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
711 root->path));
712 _rtld_objlist_push_tail(&obj->dldags, root);
713 _rtld_objlist_push_tail(&root->dagmembers, obj);
715 for (needed = obj->needed; needed != NULL; needed = needed->next)
716 if (needed->obj != NULL)
717 _rtld_init_dag1(root, needed->obj);
721 * Note, this is called only for objects loaded by dlopen().
723 static void
724 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
727 _rtld_unref_dag(root);
728 if (root->refcount == 0) { /* We are finished with some objects. */
729 Obj_Entry *obj;
730 Obj_Entry **linkp;
731 Objlist_Entry *elm;
733 /* Finalize objects that are about to be unmapped. */
734 if (do_fini_funcs)
735 _rtld_call_fini_functions(0);
737 /* Remove the DAG from all objects' DAG lists. */
738 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
739 _rtld_objlist_remove(&elm->obj->dldags, root);
741 /* Remove the DAG from the RTLD_GLOBAL list. */
742 if (root->globalref) {
743 root->globalref = 0;
744 _rtld_objlist_remove(&_rtld_list_global, root);
747 /* Unmap all objects that are no longer referenced. */
748 linkp = &_rtld_objlist->next;
749 while ((obj = *linkp) != NULL) {
750 if (obj->refcount == 0) {
751 dbg(("unloading \"%s\"", obj->path));
752 if (obj->ehdr != MAP_FAILED)
753 munmap(obj->ehdr, _rtld_pagesz);
754 munmap(obj->mapbase, obj->mapsize);
755 _rtld_objlist_remove(&_rtld_list_global, obj);
756 _rtld_linkmap_delete(obj);
757 *linkp = obj->next;
758 _rtld_objcount--;
759 _rtld_obj_free(obj);
760 } else
761 linkp = &obj->next;
763 _rtld_objtail = linkp;
767 void
768 _rtld_ref_dag(Obj_Entry *root)
770 const Needed_Entry *needed;
772 assert(root);
774 ++root->refcount;
776 dbg(("incremented reference on \"%s\" (%d)", root->path,
777 root->refcount));
778 for (needed = root->needed; needed != NULL;
779 needed = needed->next) {
780 if (needed->obj != NULL)
781 _rtld_ref_dag(needed->obj);
785 static void
786 _rtld_unref_dag(Obj_Entry *root)
789 assert(root);
790 assert(root->refcount != 0);
792 --root->refcount;
793 dbg(("decremented reference on \"%s\" (%d)", root->path,
794 root->refcount));
796 if (root->refcount == 0) {
797 const Needed_Entry *needed;
799 for (needed = root->needed; needed != NULL;
800 needed = needed->next) {
801 if (needed->obj != NULL)
802 _rtld_unref_dag(needed->obj);
807 __strong_alias(__dlclose,dlclose)
809 dlclose(void *handle)
811 Obj_Entry *root = _rtld_dlcheck(handle);
813 if (root == NULL)
814 return -1;
816 _rtld_debug.r_state = RT_DELETE;
817 _rtld_debug_state();
819 --root->dl_refcount;
820 _rtld_unload_object(root, true);
822 _rtld_debug.r_state = RT_CONSISTENT;
823 _rtld_debug_state();
825 return 0;
828 __strong_alias(__dlerror,dlerror)
829 char *
830 dlerror(void)
832 char *msg = error_message;
834 error_message = NULL;
835 return msg;
838 __strong_alias(__dlopen,dlopen)
839 void *
840 dlopen(const char *name, int mode)
842 Obj_Entry **old_obj_tail = _rtld_objtail;
843 Obj_Entry *obj = NULL;
844 int flags = _RTLD_DLOPEN;
845 bool nodelete;
846 bool now;
848 flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
849 flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
851 nodelete = (mode & RTLD_NODELETE) ? true : false;
852 now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
854 _rtld_debug.r_state = RT_ADD;
855 _rtld_debug_state();
857 if (name == NULL) {
858 obj = _rtld_objmain;
859 obj->refcount++;
860 } else
861 obj = _rtld_load_library(name, _rtld_objmain, flags);
864 if (obj != NULL) {
865 ++obj->dl_refcount;
866 if (*old_obj_tail != NULL) { /* We loaded something new. */
867 assert(*old_obj_tail == obj);
869 if (_rtld_load_needed_objects(obj, flags) == -1 ||
870 (_rtld_init_dag(obj),
871 _rtld_relocate_objects(obj,
872 (now || obj->z_now))) == -1) {
873 _rtld_unload_object(obj, false);
874 obj->dl_refcount--;
875 obj = NULL;
876 } else {
877 _rtld_call_init_functions();
880 if (obj != NULL) {
881 if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
882 dbg(("dlopen obj %s nodelete", obj->path));
883 _rtld_ref_dag(obj);
884 obj->z_nodelete = obj->ref_nodel = true;
888 _rtld_debug.r_state = RT_CONSISTENT;
889 _rtld_debug_state();
891 return obj;
895 * Find a symbol in the main program.
897 void *
898 _rtld_objmain_sym(const char *name)
900 unsigned long hash;
901 const Elf_Sym *def;
902 const Obj_Entry *obj;
903 DoneList donelist;
905 hash = _rtld_elf_hash(name);
906 obj = _rtld_objmain;
907 _rtld_donelist_init(&donelist);
909 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false,
910 &donelist);
912 if (def != NULL)
913 return obj->relocbase + def->st_value;
914 return NULL;
917 #ifdef __powerpc__
918 static void *
919 hackish_return_address(void)
921 return __builtin_return_address(1);
923 #endif
925 __strong_alias(__dlsym,dlsym)
926 void *
927 dlsym(void *handle, const char *name)
929 const Obj_Entry *obj;
930 unsigned long hash;
931 const Elf_Sym *def;
932 const Obj_Entry *defobj;
933 void *retaddr;
934 DoneList donelist;
936 hash = _rtld_elf_hash(name);
937 def = NULL;
938 defobj = NULL;
940 switch ((intptr_t)handle) {
941 case (intptr_t)NULL:
942 case (intptr_t)RTLD_NEXT:
943 case (intptr_t)RTLD_DEFAULT:
944 case (intptr_t)RTLD_SELF:
945 #ifdef __powerpc__
946 retaddr = hackish_return_address();
947 #else
948 retaddr = __builtin_return_address(0);
949 #endif
950 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
951 _rtld_error("Cannot determine caller's shared object");
952 return NULL;
955 switch ((intptr_t)handle) {
956 case (intptr_t)NULL: /* Just the caller's shared object. */
957 def = _rtld_symlook_obj(name, hash, obj, false);
958 defobj = obj;
959 break;
961 case (intptr_t)RTLD_NEXT: /* Objects after callers */
962 obj = obj->next;
963 /*FALLTHROUGH*/
965 case (intptr_t)RTLD_SELF: /* Caller included */
966 for (; obj; obj = obj->next) {
967 if ((def = _rtld_symlook_obj(name, hash, obj,
968 false)) != NULL) {
969 defobj = obj;
970 break;
973 break;
975 case (intptr_t)RTLD_DEFAULT:
976 def = _rtld_symlook_default(name, hash, obj, &defobj,
977 false);
978 break;
980 default:
981 abort();
983 break;
985 default:
986 if ((obj = _rtld_dlcheck(handle)) == NULL)
987 return NULL;
989 _rtld_donelist_init(&donelist);
991 if (obj->mainprog) {
992 /* Search main program and all libraries loaded by it */
993 def = _rtld_symlook_list(name, hash, &_rtld_list_main,
994 &defobj, false, &donelist);
995 } else {
996 Needed_Entry fake;
997 DoneList depth;
999 /* Search the object and all the libraries loaded by it. */
1000 fake.next = NULL;
1001 fake.obj = __UNCONST(obj);
1002 fake.name = 0;
1004 _rtld_donelist_init(&depth);
1005 def = _rtld_symlook_needed(name, hash, &fake, &defobj,
1006 false, &donelist, &depth);
1009 break;
1012 if (def != NULL) {
1013 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1014 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1015 return (void *)_rtld_function_descriptor_alloc(defobj,
1016 def, 0);
1017 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1018 return defobj->relocbase + def->st_value;
1021 _rtld_error("Undefined symbol \"%s\"", name);
1022 return NULL;
1025 __strong_alias(__dladdr,dladdr)
1027 dladdr(const void *addr, Dl_info *info)
1029 const Obj_Entry *obj;
1030 const Elf_Sym *def, *best_def;
1031 void *symbol_addr;
1032 unsigned long symoffset;
1034 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1035 addr = _rtld_function_descriptor_function(addr);
1036 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1038 obj = _rtld_obj_from_addr(addr);
1039 if (obj == NULL) {
1040 _rtld_error("No shared object contains address");
1041 return 0;
1043 info->dli_fname = obj->path;
1044 info->dli_fbase = obj->mapbase;
1045 info->dli_saddr = (void *)0;
1046 info->dli_sname = NULL;
1049 * Walk the symbol list looking for the symbol whose address is
1050 * closest to the address sent in.
1052 best_def = NULL;
1053 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1054 def = obj->symtab + symoffset;
1057 * For skip the symbol if st_shndx is either SHN_UNDEF or
1058 * SHN_COMMON.
1060 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1061 continue;
1064 * If the symbol is greater than the specified address, or if it
1065 * is further away from addr than the current nearest symbol,
1066 * then reject it.
1068 symbol_addr = obj->relocbase + def->st_value;
1069 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1070 continue;
1072 /* Update our idea of the nearest symbol. */
1073 info->dli_sname = obj->strtab + def->st_name;
1074 info->dli_saddr = symbol_addr;
1075 best_def = def;
1077 /* Exact match? */
1078 if (info->dli_saddr == addr)
1079 break;
1082 #ifdef __HAVE_FUNCTION_DESCRIPTORS
1083 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
1084 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
1085 best_def, 0);
1086 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
1088 return 1;
1091 __strong_alias(__dlinfo,dlinfo)
1093 dlinfo(void *handle, int req, void *v)
1095 const Obj_Entry *obj;
1096 void *retaddr;
1098 if (handle == RTLD_SELF) {
1099 #ifdef __powerpc__
1100 retaddr = hackish_return_address();
1101 #else
1102 retaddr = __builtin_return_address(0);
1103 #endif
1104 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
1105 _rtld_error("Cannot determine caller's shared object");
1106 return -1;
1108 } else {
1109 if ((obj = _rtld_dlcheck(handle)) == NULL) {
1110 _rtld_error("Invalid handle");
1111 return -1;
1115 switch (req) {
1116 case RTLD_DI_LINKMAP:
1118 const struct link_map **map = v;
1120 *map = &obj->linkmap;
1121 break;
1124 default:
1125 _rtld_error("Invalid request");
1126 return -1;
1129 return 0;
1132 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
1134 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
1136 struct dl_phdr_info phdr_info;
1137 const Obj_Entry *obj;
1138 int error = 0;
1140 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1141 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
1142 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
1143 STAILQ_FIRST(&obj->names)->name : obj->path;
1144 phdr_info.dlpi_phdr = obj->phdr;
1145 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
1146 #if 1
1147 phdr_info.dlpi_tls_modid = 0;
1148 phdr_info.dlpi_tls_data = 0;
1149 #else
1150 phdr_info.dlpi_tls_modid = obj->tlsindex;
1151 phdr_info.dlpi_tls_data = obj->tlsinit;
1152 #endif
1153 phdr_info.dlpi_adds = _rtld_objloads;
1154 phdr_info.dlpi_subs = _rtld_objloads - _rtld_objcount;
1156 error = callback(&phdr_info, sizeof(phdr_info), param);
1157 if (error)
1158 break;
1161 return error;
1165 * Error reporting function. Use it like printf. If formats the message
1166 * into a buffer, and sets things up so that the next call to dlerror()
1167 * will return the message.
1169 void
1170 _rtld_error(const char *fmt,...)
1172 static char buf[512];
1173 va_list ap;
1175 va_start(ap, fmt);
1176 xvsnprintf(buf, sizeof buf, fmt, ap);
1177 error_message = buf;
1178 va_end(ap);
1181 void
1182 _rtld_debug_state(void)
1185 /* do nothing */
1188 void
1189 _rtld_linkmap_add(Obj_Entry *obj)
1191 struct link_map *l = &obj->linkmap;
1192 struct link_map *prev;
1194 obj->linkmap.l_name = obj->path;
1195 obj->linkmap.l_addr = obj->relocbase;
1196 obj->linkmap.l_ld = obj->dynamic;
1197 #ifdef __mips__
1198 /* XXX This field is not standard and will be removed eventually. */
1199 obj->linkmap.l_offs = obj->relocbase;
1200 #endif
1202 if (_rtld_debug.r_map == NULL) {
1203 _rtld_debug.r_map = l;
1204 return;
1208 * Scan to the end of the list, but not past the entry for the
1209 * dynamic linker, which we want to keep at the very end.
1211 for (prev = _rtld_debug.r_map;
1212 prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
1213 prev = prev->l_next);
1215 l->l_prev = prev;
1216 l->l_next = prev->l_next;
1217 if (l->l_next != NULL)
1218 l->l_next->l_prev = l;
1219 prev->l_next = l;
1222 void
1223 _rtld_linkmap_delete(Obj_Entry *obj)
1225 struct link_map *l = &obj->linkmap;
1227 if (l->l_prev == NULL) {
1228 if ((_rtld_debug.r_map = l->l_next) != NULL)
1229 l->l_next->l_prev = NULL;
1230 return;
1232 if ((l->l_prev->l_next = l->l_next) != NULL)
1233 l->l_next->l_prev = l->l_prev;
1236 static Obj_Entry *
1237 _rtld_obj_from_addr(const void *addr)
1239 Obj_Entry *obj;
1241 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1242 if (addr < (void *) obj->mapbase)
1243 continue;
1244 if (addr < (void *) (obj->mapbase + obj->mapsize))
1245 return obj;
1247 return NULL;
1250 static void
1251 _rtld_objlist_clear(Objlist *list)
1253 while (!SIMPLEQ_EMPTY(list)) {
1254 Objlist_Entry* elm = SIMPLEQ_FIRST(list);
1255 SIMPLEQ_REMOVE_HEAD(list, link);
1256 xfree(elm);
1260 static void
1261 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
1263 Objlist_Entry *elm;
1265 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
1266 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1267 xfree(elm);