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