rtld.c revision 1.121 1 /* $NetBSD: rtld.c,v 1.121 2008/09/27 03:52:05 macallan 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.121 2008/09/27 03:52:05 macallan Exp $");
44 #endif /* not lint */
45
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <sys/param.h>
55 #include <sys/mman.h>
56 #include <dirent.h>
57
58 #include <ctype.h>
59
60 #include <dlfcn.h>
61 #include "debug.h"
62 #include "rtld.h"
63
64 #if !defined(lint)
65 #include "sysident.h"
66 #endif
67
68 /*
69 * Function declarations.
70 */
71 static void _rtld_init(caddr_t, caddr_t, const char *);
72 static void _rtld_exit(void);
73
74 Elf_Addr _rtld(Elf_Addr *, Elf_Addr);
75
76
77 /*
78 * Data declarations.
79 */
80 static char *error_message; /* Message for dlopen(), or NULL */
81
82 struct r_debug _rtld_debug; /* for GDB; */
83 bool _rtld_trust; /* False for setuid and setgid programs */
84 Obj_Entry *_rtld_objlist; /* Head of linked list of shared objects */
85 Obj_Entry **_rtld_objtail; /* Link field of last object in list */
86 Obj_Entry *_rtld_objmain; /* The main program shared object */
87 Obj_Entry _rtld_objself; /* The dynamic linker shared object */
88 const char _rtld_path[] = _PATH_RTLD;
89
90 /* Initialize a fake symbol for resolving undefined weak references. */
91 Elf_Sym _rtld_sym_zero = {
92 .st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
93 .st_shndx = SHN_ABS,
94 };
95 int _rtld_pagesz; /* Page size, as provided by kernel */
96
97 Search_Path *_rtld_default_paths;
98 Search_Path *_rtld_paths;
99
100 Library_Xform *_rtld_xforms;
101
102 /*
103 * Global declarations normally provided by crt0.
104 */
105 char *__progname;
106 char **environ;
107
108 #if defined(RTLD_DEBUG)
109 #ifndef __sh__
110 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
111 #else /* 32-bit SuperH */
112 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
113 #endif
114 #endif /* RTLD_DEBUG */
115 extern Elf_Dyn _DYNAMIC;
116
117 static void _rtld_call_fini_functions(int);
118 static void _rtld_call_init_functions(void);
119 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
120 static void _rtld_initlist_tsort(Objlist *, int);
121 static Obj_Entry *_rtld_dlcheck(void *);
122 static void _rtld_init_dag(Obj_Entry *);
123 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
124 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
125 static void _rtld_objlist_clear(Objlist *);
126 static void _rtld_unload_object(Obj_Entry *, bool);
127 static void _rtld_unref_dag(Obj_Entry *);
128 static Obj_Entry *_rtld_obj_from_addr(const void *);
129
130 static void
131 _rtld_call_fini_functions(int force)
132 {
133 Objlist_Entry *elm;
134 Objlist finilist;
135 Obj_Entry *obj;
136
137 dbg(("_rtld_call_fini_functions(%d)", force));
138
139 SIMPLEQ_INIT(&finilist);
140 _rtld_initlist_tsort(&finilist, 1);
141
142 /* First pass: objects _not_ marked with DF_1_INITFIRST. */
143 SIMPLEQ_FOREACH(elm, &finilist, link) {
144 obj = elm->obj;
145 if (obj->refcount > 0 && !force) {
146 continue;
147 }
148 if (obj->fini == NULL || obj->fini_called || obj->initfirst) {
149 continue;
150 }
151 dbg (("calling fini function %s at %p", obj->path,
152 (void *)obj->fini));
153 obj->fini_called = 1;
154 (*obj->fini)();
155 }
156
157 /* Second pass: objects marked with DF_1_INITFIRST. */
158 SIMPLEQ_FOREACH(elm, &finilist, link) {
159 obj = elm->obj;
160 if (obj->refcount > 0 && !force) {
161 continue;
162 }
163 if (obj->fini == NULL || obj->fini_called) {
164 continue;
165 }
166 dbg (("calling fini function %s at %p (DF_1_INITFIRST)",
167 obj->path, (void *)obj->fini));
168 obj->fini_called = 1;
169 (*obj->fini)();
170 }
171
172 _rtld_objlist_clear(&finilist);
173 }
174
175 static void
176 _rtld_call_init_functions()
177 {
178 Objlist_Entry *elm;
179 Objlist initlist;
180 Obj_Entry *obj;
181
182 dbg(("_rtld_call_init_functions()"));
183 SIMPLEQ_INIT(&initlist);
184 _rtld_initlist_tsort(&initlist, 0);
185
186 /* First pass: objects marked with DF_1_INITFIRST. */
187 SIMPLEQ_FOREACH(elm, &initlist, link) {
188 obj = elm->obj;
189 if (obj->init == NULL || obj->init_called || !obj->initfirst) {
190 continue;
191 }
192 dbg (("calling init function %s at %p (DF_1_INITFIRST)",
193 obj->path, (void *)obj->init));
194 obj->init_called = 1;
195 (*obj->init)();
196 }
197
198 /* Second pass: all other objects. */
199 SIMPLEQ_FOREACH(elm, &initlist, link) {
200 obj = elm->obj;
201 if (obj->init == NULL || obj->init_called) {
202 continue;
203 }
204 dbg (("calling init function %s at %p", obj->path,
205 (void *)obj->init));
206 obj->init_called = 1;
207 (*obj->init)();
208 }
209
210 _rtld_objlist_clear(&initlist);
211 }
212
213 /*
214 * Initialize the dynamic linker. The argument is the address at which
215 * the dynamic linker has been mapped into memory. The primary task of
216 * this function is to create an Obj_Entry for the dynamic linker and
217 * to resolve the PLT relocation for platforms that need it (those that
218 * define __HAVE_FUNCTION_DESCRIPTORS
219 */
220 static void
221 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
222 {
223
224 /* Conjure up an Obj_Entry structure for the dynamic linker. */
225 _rtld_objself.path = __UNCONST(_rtld_path);
226 _rtld_objself.pathlen = sizeof(_rtld_path)-1;
227 _rtld_objself.rtld = true;
228 _rtld_objself.mapbase = mapbase;
229 _rtld_objself.relocbase = relocbase;
230 _rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
231 _rtld_objself.strtab = "_rtld_sym_zero";
232
233 /*
234 * Set value to -relocabase so that
235 * _rtld_objself.relocbase + _rtld_smy_zero.st_value == 0
236 * This allows unresolved references to weak symbols to be computed
237 * to value a value of 0.
238 */
239 _rtld_sym_zero.st_value = -(uintptr_t)relocbase;
240
241 _rtld_digest_dynamic(_rtld_path, &_rtld_objself);
242 assert(!_rtld_objself.needed);
243 #if !defined(__hppa__)
244 assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
245 #else
246 _rtld_relocate_plt_objects(&_rtld_objself);
247 #endif
248 #if !defined(__mips__) && !defined(__hppa__)
249 assert(!_rtld_objself.pltgot);
250 #endif
251 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
252 /* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
253 assert(!_rtld_objself.textrel);
254 #endif
255
256 _rtld_add_paths(execname, &_rtld_default_paths,
257 RTLD_DEFAULT_LIBRARY_PATH);
258
259 /*
260 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
261 */
262 _rtld_objlist = &_rtld_objself;
263
264 /* Make the object list empty again. */
265 _rtld_objlist = NULL;
266 _rtld_objtail = &_rtld_objlist;
267
268 _rtld_debug.r_brk = _rtld_debug_state;
269 _rtld_debug.r_state = RT_CONSISTENT;
270 }
271
272 /*
273 * Cleanup procedure. It will be called (by the atexit() mechanism) just
274 * before the process exits.
275 */
276 static void
277 _rtld_exit(void)
278 {
279 dbg(("rtld_exit()"));
280
281 _rtld_call_fini_functions(1);
282 }
283
284 /*
285 * Main entry point for dynamic linking. The argument is the stack
286 * pointer. The stack is expected to be laid out as described in the
287 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
288 * the stack pointer points to a word containing ARGC. Following that
289 * in the stack is a null-terminated sequence of pointers to argument
290 * strings. Then comes a null-terminated sequence of pointers to
291 * environment strings. Finally, there is a sequence of "auxiliary
292 * vector" entries.
293 *
294 * This function returns the entry point for the main program, the dynamic
295 * linker's exit procedure in sp[0], and a pointer to the main object in
296 * sp[1].
297 */
298 Elf_Addr
299 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
300 {
301 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
302 *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
303 *pAUX_ruid, *pAUX_rgid;
304 const AuxInfo *pAUX_pagesz;
305 char **env;
306 const AuxInfo *aux;
307 const AuxInfo *auxp;
308 Elf_Addr *const osp = sp;
309 bool bind_now = 0;
310 const char *ld_bind_now;
311 const char **argv;
312 const char *execname;
313 long argc;
314 const char **real___progname;
315 const Obj_Entry **real___mainprog_obj;
316 char ***real_environ;
317 #if defined(RTLD_DEBUG)
318 int i = 0;
319 #endif
320
321 /*
322 * On entry, the dynamic linker itself has not been relocated yet.
323 * Be very careful not to reference any global data until after
324 * _rtld_init has returned. It is OK to reference file-scope statics
325 * and string constants, and to call static and global functions.
326 */
327 /* Find the auxiliary vector on the stack. */
328 /* first Elf_Word reserved to address of exit routine */
329 #if defined(RTLD_DEBUG)
330 debug = 1;
331 dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
332 (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
333 dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
334 &_DYNAMIC));
335 dbg(("_ctype_ is %p", _ctype_));
336 #endif
337
338 sp += 2; /* skip over return argument space */
339 argv = (const char **) &sp[1];
340 argc = *(long *)sp;
341 sp += 2 + argc; /* Skip over argc, arguments, and NULL
342 * terminator */
343 env = (char **) sp;
344 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
345 #if defined(RTLD_DEBUG)
346 dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
347 #endif
348 }
349 aux = (const AuxInfo *) sp;
350
351 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
352 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
353 pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
354 pAUX_pagesz = NULL;
355
356 execname = NULL;
357
358 /* Digest the auxiliary vector. */
359 for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
360 switch (auxp->a_type) {
361 case AT_BASE:
362 pAUX_base = auxp;
363 break;
364 case AT_ENTRY:
365 pAUX_entry = auxp;
366 break;
367 case AT_EXECFD:
368 pAUX_execfd = auxp;
369 break;
370 case AT_PHDR:
371 pAUX_phdr = auxp;
372 break;
373 case AT_PHENT:
374 pAUX_phent = auxp;
375 break;
376 case AT_PHNUM:
377 pAUX_phnum = auxp;
378 break;
379 #ifdef AT_EUID
380 case AT_EUID:
381 pAUX_euid = auxp;
382 break;
383 case AT_RUID:
384 pAUX_ruid = auxp;
385 break;
386 case AT_EGID:
387 pAUX_egid = auxp;
388 break;
389 case AT_RGID:
390 pAUX_rgid = auxp;
391 break;
392 #endif
393 #ifdef AT_SUN_EXECNAME
394 case AT_SUN_EXECNAME:
395 execname = (const char *)(const void *)auxp->a_v;
396 break;
397 #endif
398 case AT_PAGESZ:
399 pAUX_pagesz = auxp;
400 break;
401 }
402 }
403
404 /* Initialize and relocate ourselves. */
405 if (pAUX_base == NULL) {
406 _rtld_error("Bad pAUX_base");
407 _rtld_die();
408 }
409 assert(pAUX_pagesz != NULL);
410 _rtld_pagesz = (int)pAUX_pagesz->a_v;
411 _rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
412
413 __progname = _rtld_objself.path;
414 environ = env;
415
416 _rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
417 (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
418 ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
419 (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
420
421 ld_bind_now = getenv("LD_BIND_NOW");
422 if (ld_bind_now != NULL && *ld_bind_now != '\0')
423 bind_now = true;
424 if (_rtld_trust) {
425 #ifdef DEBUG
426 const char *ld_debug = getenv("LD_DEBUG");
427 #ifdef RTLD_DEBUG
428 debug = 0;
429 #endif
430 if (ld_debug != NULL && *ld_debug != '\0')
431 debug = 1;
432 #endif
433 _rtld_add_paths(execname, &_rtld_paths,
434 getenv("LD_LIBRARY_PATH"));
435 } else {
436 execname = NULL;
437 unsetenv("LD_DEBUG");
438 unsetenv("LD_LIBRARY_PATH");
439 }
440 _rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
441 _PATH_LD_HINTS);
442 dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
443 _rtld_objself.mapbase, _rtld_objself.relocbase));
444
445 /*
446 * Load the main program, or process its program header if it is
447 * already loaded.
448 */
449 if (pAUX_execfd != NULL) { /* Load the main program. */
450 int fd = pAUX_execfd->a_v;
451 const char *obj_name = argv[0] ? argv[0] : "main program";
452 dbg(("loading main program"));
453 _rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
454 close(fd);
455 if (_rtld_objmain == NULL)
456 _rtld_die();
457 } else { /* Main program already loaded. */
458 const Elf_Phdr *phdr;
459 int phnum;
460 caddr_t entry;
461
462 dbg(("processing main program's program header"));
463 assert(pAUX_phdr != NULL);
464 phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
465 assert(pAUX_phnum != NULL);
466 phnum = pAUX_phnum->a_v;
467 assert(pAUX_phent != NULL);
468 assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
469 assert(pAUX_entry != NULL);
470 entry = (caddr_t) pAUX_entry->a_v;
471 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
472 _rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
473 "main program");
474 _rtld_objmain->pathlen = strlen(_rtld_objmain->path);
475 }
476
477 _rtld_objmain->mainprog = true;
478
479 /*
480 * Get the actual dynamic linker pathname from the executable if
481 * possible. (It should always be possible.) That ensures that
482 * gdb will find the right dynamic linker even if a non-standard
483 * one is being used.
484 */
485 if (_rtld_objmain->interp != NULL &&
486 strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
487 _rtld_objself.path = xstrdup(_rtld_objmain->interp);
488 dbg(("actual dynamic linker is %s", _rtld_objself.path));
489
490 _rtld_digest_dynamic(execname, _rtld_objmain);
491
492 /* Link the main program into the list of objects. */
493 *_rtld_objtail = _rtld_objmain;
494 _rtld_objtail = &_rtld_objmain->next;
495
496 _rtld_linkmap_add(_rtld_objmain);
497 _rtld_linkmap_add(&_rtld_objself);
498
499 ++_rtld_objmain->refcount;
500 _rtld_objmain->mainref = 1;
501 _rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
502
503 if (_rtld_trust) {
504 /*
505 * Pre-load user-specified objects after the main program
506 * but before any shared object dependencies.
507 */
508 dbg(("preloading objects"));
509 if (_rtld_preload(getenv("LD_PRELOAD")) == -1)
510 _rtld_die();
511 } else
512 unsetenv("LD_PRELOAD");
513
514 dbg(("loading needed objects"));
515 if (_rtld_load_needed_objects(_rtld_objmain, RTLD_MAIN) == -1)
516 _rtld_die();
517
518 dbg(("relocating objects"));
519 if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
520 _rtld_die();
521
522 dbg(("doing copy relocations"));
523 if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
524 _rtld_die();
525
526 /*
527 * Set the __progname, environ and, __mainprog_obj before
528 * calling anything that might use them.
529 */
530 real___progname = _rtld_objmain_sym("__progname");
531 if (real___progname) {
532 if (argv[0] != NULL) {
533 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
534 (*real___progname) = argv[0];
535 else
536 (*real___progname)++;
537 } else {
538 (*real___progname) = NULL;
539 }
540 }
541 real_environ = _rtld_objmain_sym("environ");
542 if (real_environ)
543 *real_environ = environ;
544 /*
545 * Set __mainprog_obj for old binaries.
546 */
547 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
548 if (real___mainprog_obj)
549 *real___mainprog_obj = _rtld_objmain;
550
551 dbg(("calling _init functions"));
552 _rtld_call_init_functions();
553
554 dbg(("control at program entry point = %p, obj = %p, exit = %p",
555 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
556
557 /*
558 * Return with the entry point and the exit procedure in at the top
559 * of stack.
560 */
561
562 _rtld_debug_state(); /* say hello to gdb! */
563
564 ((void **) osp)[0] = _rtld_exit;
565 ((void **) osp)[1] = _rtld_objmain;
566 return (Elf_Addr) _rtld_objmain->entry;
567 }
568
569 void
570 _rtld_die(void)
571 {
572 const char *msg = dlerror();
573
574 if (msg == NULL)
575 msg = "Fatal error";
576 xerrx(1, "%s", msg);
577 }
578
579 static Obj_Entry *
580 _rtld_dlcheck(void *handle)
581 {
582 Obj_Entry *obj;
583
584 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
585 if (obj == (Obj_Entry *) handle)
586 break;
587
588 if (obj == NULL || obj->dl_refcount == 0) {
589 xwarnx("Invalid shared object handle %p", handle);
590 return NULL;
591 }
592 return obj;
593 }
594
595 static void
596 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
597 {
598 Needed_Entry* elm;
599
600 /* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
601
602 if (obj->init_done)
603 return;
604 obj->init_done = 1;
605
606 for (elm = obj->needed; elm != NULL; elm = elm->next) {
607 if (elm->obj != NULL) {
608 _rtld_initlist_visit(list, elm->obj, rev);
609 }
610 }
611
612 if (rev) {
613 _rtld_objlist_push_head(list, obj);
614 } else {
615 _rtld_objlist_push_tail(list, obj);
616 }
617 }
618
619 static void
620 _rtld_initlist_tsort(Objlist* list, int rev)
621 {
622 dbg(("_rtld_initlist_tsort"));
623
624 Obj_Entry* obj;
625
626 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
627 obj->init_done = 0;
628 }
629
630 for (obj = _rtld_objlist->next; obj; obj = obj->next) {
631 _rtld_initlist_visit(list, obj, rev);
632 }
633 }
634
635 static void
636 _rtld_init_dag(Obj_Entry *root)
637 {
638
639 _rtld_init_dag1(root, root);
640 }
641
642 static void
643 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
644 {
645 const Needed_Entry *needed;
646
647 if (!obj->mainref) {
648 if (_rtld_objlist_find(&obj->dldags, root))
649 return;
650 rdbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
651 root->path));
652 _rtld_objlist_push_tail(&obj->dldags, root);
653 _rtld_objlist_push_tail(&root->dagmembers, obj);
654 }
655 for (needed = obj->needed; needed != NULL; needed = needed->next)
656 if (needed->obj != NULL)
657 _rtld_init_dag1(root, needed->obj);
658 }
659
660 /*
661 * Note, this is called only for objects loaded by dlopen().
662 */
663 static void
664 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
665 {
666
667 _rtld_unref_dag(root);
668 if (root->refcount == 0) { /* We are finished with some objects. */
669 Obj_Entry *obj;
670 Obj_Entry **linkp;
671 Objlist_Entry *elm;
672
673 /* Finalize objects that are about to be unmapped. */
674 if (do_fini_funcs)
675 _rtld_call_fini_functions(0);
676
677 /* Remove the DAG from all objects' DAG lists. */
678 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
679 _rtld_objlist_remove(&elm->obj->dldags, root);
680
681 /* Remove the DAG from the RTLD_GLOBAL list. */
682 if (root->globalref) {
683 root->globalref = 0;
684 _rtld_objlist_remove(&_rtld_list_global, root);
685 }
686
687 /* Unmap all objects that are no longer referenced. */
688 linkp = &_rtld_objlist->next;
689 while ((obj = *linkp) != NULL) {
690 if (obj->refcount == 0) {
691 #ifdef RTLD_DEBUG
692 dbg(("unloading \"%s\"", obj->path));
693 #endif
694 if (obj->ehdr != MAP_FAILED)
695 munmap(obj->ehdr, _rtld_pagesz);
696 munmap(obj->mapbase, obj->mapsize);
697 _rtld_objlist_remove(&_rtld_list_global, obj);
698 _rtld_linkmap_delete(obj);
699 *linkp = obj->next;
700 _rtld_obj_free(obj);
701 } else
702 linkp = &obj->next;
703 }
704 _rtld_objtail = linkp;
705 }
706 }
707
708 static void
709 _rtld_unref_dag(Obj_Entry *root)
710 {
711
712 assert(root);
713 assert(root->refcount != 0);
714 --root->refcount;
715 if (root->refcount == 0) {
716 const Needed_Entry *needed;
717
718 for (needed = root->needed; needed != NULL;
719 needed = needed->next) {
720 if (needed->obj != NULL)
721 _rtld_unref_dag(needed->obj);
722 }
723 }
724 }
725
726 __strong_alias(__dlclose,dlclose)
727 int
728 dlclose(void *handle)
729 {
730 Obj_Entry *root = _rtld_dlcheck(handle);
731
732 if (root == NULL)
733 return -1;
734
735 _rtld_debug.r_state = RT_DELETE;
736 _rtld_debug_state();
737
738 --root->dl_refcount;
739 _rtld_unload_object(root, true);
740
741 _rtld_debug.r_state = RT_CONSISTENT;
742 _rtld_debug_state();
743
744 return 0;
745 }
746
747 __strong_alias(__dlerror,dlerror)
748 char *
749 dlerror(void)
750 {
751 char *msg = error_message;
752
753 error_message = NULL;
754 return msg;
755 }
756
757 __strong_alias(__dlopen,dlopen)
758 void *
759 dlopen(const char *name, int mode)
760 {
761 Obj_Entry **old_obj_tail = _rtld_objtail;
762 Obj_Entry *obj = NULL;
763
764 _rtld_debug.r_state = RT_ADD;
765 _rtld_debug_state();
766
767 if (name == NULL) {
768 obj = _rtld_objmain;
769 obj->refcount++;
770 } else
771 obj = _rtld_load_library(name, _rtld_objmain, mode);
772
773 if (obj != NULL) {
774 ++obj->dl_refcount;
775 if (*old_obj_tail != NULL) { /* We loaded something new. */
776 assert(*old_obj_tail == obj);
777
778 if (_rtld_load_needed_objects(obj, mode) == -1 ||
779 (_rtld_init_dag(obj),
780 _rtld_relocate_objects(obj,
781 ((mode & 3) == RTLD_NOW))) == -1) {
782 _rtld_unload_object(obj, false);
783 obj->dl_refcount--;
784 obj = NULL;
785 } else {
786 _rtld_call_init_functions();
787 }
788 }
789 }
790 _rtld_debug.r_state = RT_CONSISTENT;
791 _rtld_debug_state();
792
793 return obj;
794 }
795
796 /*
797 * Find a symbol in the main program.
798 */
799 void *
800 _rtld_objmain_sym(const char *name)
801 {
802 unsigned long hash;
803 const Elf_Sym *def;
804 const Obj_Entry *obj;
805
806 hash = _rtld_elf_hash(name);
807 obj = _rtld_objmain;
808
809 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false);
810
811 if (def != NULL)
812 return obj->relocbase + def->st_value;
813 return(NULL);
814 }
815
816 #ifdef __powerpc__
817 static void *
818 hackish_return_address(void)
819 {
820 return __builtin_return_address(1);
821 }
822 #endif
823
824 __strong_alias(__dlsym,dlsym)
825 void *
826 dlsym(void *handle, const char *name)
827 {
828 const Obj_Entry *obj;
829 unsigned long hash;
830 const Elf_Sym *def;
831 const Obj_Entry *defobj;
832 void *retaddr;
833
834 hash = _rtld_elf_hash(name);
835 def = NULL;
836 defobj = NULL;
837
838 switch ((intptr_t)handle) {
839 case (intptr_t)NULL:
840 case (intptr_t)RTLD_NEXT:
841 case (intptr_t)RTLD_DEFAULT:
842 case (intptr_t)RTLD_SELF:
843 #ifdef __powerpc__
844 retaddr = hackish_return_address();
845 #else
846 retaddr = __builtin_return_address(0);
847 #endif
848 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
849 _rtld_error("Cannot determine caller's shared object");
850 return NULL;
851 }
852
853 switch ((intptr_t)handle) {
854 case (intptr_t)NULL: /* Just the caller's shared object. */
855 def = _rtld_symlook_obj(name, hash, obj, false);
856 defobj = obj;
857 break;
858
859 case (intptr_t)RTLD_NEXT: /* Objects after callers */
860 obj = obj->next;
861 /*FALLTHROUGH*/
862
863 case (intptr_t)RTLD_SELF: /* Caller included */
864 for (; obj; obj = obj->next) {
865 if ((def = _rtld_symlook_obj(name, hash, obj,
866 false)) != NULL) {
867 defobj = obj;
868 break;
869 }
870 }
871 break;
872
873 case (intptr_t)RTLD_DEFAULT:
874 def = _rtld_symlook_default(name, hash, obj, &defobj,
875 false);
876 break;
877
878 default:
879 abort();
880 }
881 break;
882
883 default:
884 if ((obj = _rtld_dlcheck(handle)) == NULL)
885 return NULL;
886
887 if (obj->mainprog) {
888 /* Search main program and all libraries loaded by it */
889 def = _rtld_symlook_list(name, hash, &_rtld_list_main,
890 &defobj, false);
891 } else {
892 /*
893 * XXX - This isn't correct. The search should include
894 * the whole DAG rooted at the given object.
895 */
896 def = _rtld_symlook_obj(name, hash, obj, false);
897 defobj = obj;
898 }
899 break;
900 }
901
902 if (def != NULL) {
903 #ifdef __HAVE_FUNCTION_DESCRIPTORS
904 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
905 return (void *)_rtld_function_descriptor_alloc(defobj,
906 def, 0);
907 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
908 return defobj->relocbase + def->st_value;
909 }
910
911 _rtld_error("Undefined symbol \"%s\"", name);
912 return NULL;
913 }
914
915 __strong_alias(__dladdr,dladdr)
916 int
917 dladdr(const void *addr, Dl_info *info)
918 {
919 const Obj_Entry *obj;
920 const Elf_Sym *def, *best_def;
921 void *symbol_addr;
922 unsigned long symoffset;
923
924 #ifdef __HAVE_FUNCTION_DESCRIPTORS
925 addr = _rtld_function_descriptor_function(addr);
926 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
927
928 obj = _rtld_obj_from_addr(addr);
929 if (obj == NULL) {
930 _rtld_error("No shared object contains address");
931 return 0;
932 }
933 info->dli_fname = obj->path;
934 info->dli_fbase = obj->mapbase;
935 info->dli_saddr = (void *)0;
936 info->dli_sname = NULL;
937
938 /*
939 * Walk the symbol list looking for the symbol whose address is
940 * closest to the address sent in.
941 */
942 best_def = NULL;
943 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
944 def = obj->symtab + symoffset;
945
946 /*
947 * For skip the symbol if st_shndx is either SHN_UNDEF or
948 * SHN_COMMON.
949 */
950 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
951 continue;
952
953 /*
954 * If the symbol is greater than the specified address, or if it
955 * is further away from addr than the current nearest symbol,
956 * then reject it.
957 */
958 symbol_addr = obj->relocbase + def->st_value;
959 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
960 continue;
961
962 /* Update our idea of the nearest symbol. */
963 info->dli_sname = obj->strtab + def->st_name;
964 info->dli_saddr = symbol_addr;
965 best_def = def;
966
967 /* Exact match? */
968 if (info->dli_saddr == addr)
969 break;
970 }
971
972 #ifdef __HAVE_FUNCTION_DESCRIPTORS
973 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
974 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
975 best_def, 0);
976 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
977
978 return 1;
979 }
980
981 /*
982 * Error reporting function. Use it like printf. If formats the message
983 * into a buffer, and sets things up so that the next call to dlerror()
984 * will return the message.
985 */
986 void
987 _rtld_error(const char *fmt,...)
988 {
989 static char buf[512];
990 va_list ap;
991
992 va_start(ap, fmt);
993 xvsnprintf(buf, sizeof buf, fmt, ap);
994 error_message = buf;
995 va_end(ap);
996 }
997
998 void
999 _rtld_debug_state(void)
1000 {
1001
1002 /* do nothing */
1003 }
1004
1005 void
1006 _rtld_linkmap_add(Obj_Entry *obj)
1007 {
1008 struct link_map *l = &obj->linkmap;
1009 struct link_map *prev;
1010
1011 obj->linkmap.l_name = obj->path;
1012 obj->linkmap.l_addr = obj->relocbase;
1013 obj->linkmap.l_ld = obj->dynamic;
1014 #ifdef __mips__
1015 /* XXX This field is not standard and will be removed eventually. */
1016 obj->linkmap.l_offs = obj->relocbase;
1017 #endif
1018
1019 if (_rtld_debug.r_map == NULL) {
1020 _rtld_debug.r_map = l;
1021 return;
1022 }
1023
1024 /*
1025 * Scan to the end of the list, but not past the entry for the
1026 * dynamic linker, which we want to keep at the very end.
1027 */
1028 for (prev = _rtld_debug.r_map;
1029 prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
1030 prev = prev->l_next);
1031
1032 l->l_prev = prev;
1033 l->l_next = prev->l_next;
1034 if (l->l_next != NULL)
1035 l->l_next->l_prev = l;
1036 prev->l_next = l;
1037 }
1038
1039 void
1040 _rtld_linkmap_delete(Obj_Entry *obj)
1041 {
1042 struct link_map *l = &obj->linkmap;
1043
1044 if (l->l_prev == NULL) {
1045 if ((_rtld_debug.r_map = l->l_next) != NULL)
1046 l->l_next->l_prev = NULL;
1047 return;
1048 }
1049 if ((l->l_prev->l_next = l->l_next) != NULL)
1050 l->l_next->l_prev = l->l_prev;
1051 }
1052
1053 static Obj_Entry *
1054 _rtld_obj_from_addr(const void *addr)
1055 {
1056 Obj_Entry *obj;
1057
1058 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
1059 if (addr < (void *) obj->mapbase)
1060 continue;
1061 if (addr < (void *) (obj->mapbase + obj->mapsize))
1062 return obj;
1063 }
1064 return NULL;
1065 }
1066
1067 static void
1068 _rtld_objlist_clear(Objlist *list)
1069 {
1070 while (!SIMPLEQ_EMPTY(list)) {
1071 Objlist_Entry* elm = SIMPLEQ_FIRST(list);
1072 SIMPLEQ_REMOVE_HEAD(list, link);
1073 xfree(elm);
1074 }
1075 }
1076
1077 static void
1078 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
1079 {
1080 Objlist_Entry *elm;
1081
1082 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
1083 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1084 xfree(elm);
1085 }
1086 }
1087