rtld.c revision 1.53 1 /* $NetBSD: rtld.c,v 1.53 2002/08/26 21:09:55 christos Exp $ */
2
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by John Polstra.
19 * 4. The name of the author may not be used to endorse or promote products
20 * derived from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 /*
35 * Dynamic linker for ELF.
36 *
37 * John Polstra <jdp (at) polstra.com>.
38 */
39
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <sys/param.h>
49 #include <sys/mman.h>
50 #include <dirent.h>
51
52 #include <ctype.h>
53
54 #include <dlfcn.h>
55 #include "debug.h"
56 #include "rtld.h"
57
58 #if !defined(lint)
59 #include "sysident.h"
60 #endif
61
62 #define END_SYM "_end"
63
64 /*
65 * Debugging support.
66 */
67
68 typedef void (*funcptr) __P((void));
69
70 /*
71 * Function declarations.
72 */
73 static void _rtld_init __P((caddr_t, int));
74 static void _rtld_exit __P((void));
75
76 Elf_Addr _rtld __P((Elf_Addr *));
77
78
79 /*
80 * Data declarations.
81 */
82 static char *error_message; /* Message for dlopen(), or NULL */
83
84 struct r_debug _rtld_debug; /* for GDB; */
85 bool _rtld_trust; /* False for setuid and setgid programs */
86 Obj_Entry *_rtld_objlist; /* Head of linked list of shared objects */
87 Obj_Entry **_rtld_objtail; /* Link field of last object in list */
88 Obj_Entry *_rtld_objmain; /* The main program shared object */
89 Obj_Entry _rtld_objself; /* The dynamic linker shared object */
90 char _rtld_path[] = _PATH_RTLD;
91 unsigned long _rtld_curmark; /* Current mark value */
92 Elf_Sym _rtld_sym_zero; /* For resolving undefined weak refs. */
93 #ifdef VARPSZ
94 int _rtld_pagesz; /* Page size, as provided by kernel */
95 #endif
96
97 Objlist _rtld_list_main = /* Objects loaded at program startup */
98 SIMPLEQ_HEAD_INITIALIZER(_rtld_list_main);
99
100 Search_Path *_rtld_default_paths;
101 Search_Path *_rtld_paths;
102
103 Library_Xform *_rtld_xforms;
104
105 /*
106 * Global declarations normally provided by crt0.
107 */
108 char *__progname;
109 char **environ;
110
111 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
112 extern Elf_Dyn _DYNAMIC;
113
114 static void _rtld_call_fini_functions __P((Obj_Entry *));
115 static void _rtld_call_init_functions __P((Obj_Entry *));
116 static Obj_Entry *_rtld_dlcheck __P((void *));
117 static void _rtld_init_dag __P((Obj_Entry *));
118 static void _rtld_init_dag1 __P((Obj_Entry *, Obj_Entry *));
119 static void _rtld_objlist_remove __P((Objlist *, Obj_Entry *));
120 static void _rtld_unload_object __P((Obj_Entry *, bool));
121 static void _rtld_unref_dag __P((Obj_Entry *));
122 static Obj_Entry *_rtld_obj_from_addr __P((const void *));
123
124 static void
125 _rtld_call_fini_functions(first)
126 Obj_Entry *first;
127 {
128 Obj_Entry *obj;
129
130 for (obj = first; obj != NULL; obj = obj->next)
131 if (obj->fini != NULL)
132 (*obj->fini)();
133 }
134
135 static void
136 _rtld_call_init_functions(first)
137 Obj_Entry *first;
138 {
139 if (first != NULL) {
140 _rtld_call_init_functions(first->next);
141 if (first->init != NULL)
142 (*first->init)();
143 }
144 }
145
146 /*
147 * Initialize the dynamic linker. The argument is the address at which
148 * the dynamic linker has been mapped into memory. The primary task of
149 * this function is to relocate the dynamic linker.
150 */
151 static void
152 _rtld_init(mapbase, pagesz)
153 caddr_t mapbase;
154 int pagesz;
155 {
156 Obj_Entry objself;/* The dynamic linker shared object */
157 const Elf_Ehdr *hdr = (Elf_Ehdr *) mapbase;
158 #ifdef RTLD_RELOCATE_SELF
159 int dodebug = false;
160 #else
161 int dodebug = true;
162 #endif
163 int i;
164
165 memset(&objself, 0, sizeof objself);
166
167 /* Conjure up an Obj_Entry structure for the dynamic linker. */
168 objself.path = NULL;
169 objself.rtld = true;
170 objself.mapbase = mapbase;
171 objself.phdr = (Elf_Phdr *) (mapbase + hdr->e_phoff);
172 for (i = 0; i < hdr->e_phnum; i++) {
173 if (objself.phdr[i].p_type == PT_LOAD) {
174 #ifdef VARPSZ
175 /* We can't touch _rtld_pagesz yet so we can't use round_*() */
176 #define _rnd_down(x) ((x) & ~((long)pagesz-1))
177 #define _rnd_up(x) _rnd_down((x) + pagesz - 1)
178 objself.textsize = _rnd_up(objself.phdr[i].p_vaddr + objself.phdr[i].p_memsz) - _rnd_down(objself.phdr[i].p_vaddr);
179 #undef _rnd_down
180 #undef _rnd_up
181 #else
182 objself.textsize = round_up(objself.phdr[i].p_vaddr + objself.phdr[i].p_memsz) - round_down(objself.phdr[i].p_vaddr);
183 #endif
184 break;
185 }
186 }
187
188 #if defined(__mips__)
189 /*
190 * mips and ld.so currently linked at load address,
191 * so no relocation needed
192 */
193 objself.relocbase = 0;
194 #else
195 objself.relocbase = mapbase;
196 #endif
197
198 objself.pltgot = NULL;
199
200 objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
201
202 #ifdef RTLD_RELOCATE_SELF
203 /* We have not been relocated yet, so fix the dynamic address */
204 objself.dynamic = (Elf_Dyn *)
205 ((u_long) mapbase + (char *) objself.dynamic);
206 #endif /* RTLD_RELOCATE_SELF */
207
208 _rtld_digest_dynamic(&objself);
209
210 #ifdef __alpha__
211 /* XXX XXX XXX */
212 objself.pltgot = NULL;
213 #endif
214 assert(objself.needed == NULL);
215
216 #if !defined(__arm__) && !defined(__mips__) && !defined(__i386__) && \
217 !defined(__sh__) && !defined(__vax__)
218 /* no relocation for mips/i386 */
219 assert(!objself.textrel);
220 #endif
221
222 _rtld_relocate_objects(&objself, true, dodebug);
223
224 /*
225 * Now that we relocated ourselves, we can use globals.
226 */
227 _rtld_objself = objself;
228
229 _rtld_objself.path = _rtld_path;
230 _rtld_add_paths(&_rtld_default_paths, RTLD_DEFAULT_LIBRARY_PATH, true);
231
232 /*
233 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
234 */
235 _rtld_objlist = &_rtld_objself;
236
237 /* Make the object list empty again. */
238 _rtld_objlist = NULL;
239 _rtld_objtail = &_rtld_objlist;
240
241 _rtld_debug.r_brk = _rtld_debug_state;
242 _rtld_debug.r_state = RT_CONSISTENT;
243 }
244
245 /*
246 * Cleanup procedure. It will be called (by the atexit() mechanism) just
247 * before the process exits.
248 */
249 static void
250 _rtld_exit()
251 {
252 dbg(("rtld_exit()"));
253
254 _rtld_call_fini_functions(_rtld_objlist->next);
255 }
256
257 /*
258 * Main entry point for dynamic linking. The argument is the stack
259 * pointer. The stack is expected to be laid out as described in the
260 * SVR4 ABI specification, Intel 386 Processor Supplement. Specifically,
261 * the stack pointer points to a word containing ARGC. Following that
262 * in the stack is a null-terminated sequence of pointers to argument
263 * strings. Then comes a null-terminated sequence of pointers to
264 * environment strings. Finally, there is a sequence of "auxiliary
265 * vector" entries.
266 *
267 * This function returns the entry point for the main program, the dynamic
268 * linker's exit procedure in sp[0], and a pointer to the main object in
269 * sp[1].
270 */
271 Elf_Addr
272 _rtld(sp)
273 Elf_Addr *sp;
274 {
275 const AuxInfo *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
276 *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
277 *pAUX_ruid, *pAUX_rgid;
278 #ifdef VARPSZ
279 const AuxInfo *pAUX_pagesz;
280 #endif
281 char **env;
282 const AuxInfo *aux;
283 const AuxInfo *auxp;
284 Elf_Addr *const osp = sp;
285 bool bind_now = 0;
286 const char *ld_bind_now;
287 const char **argv;
288 long argc;
289 Obj_Entry *obj;
290 const char **real___progname;
291 const Obj_Entry **real___mainprog_obj;
292 char ***real_environ;
293 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
294 int i = 0;
295 #endif
296
297 /*
298 * On entry, the dynamic linker itself has not been relocated yet.
299 * Be very careful not to reference any global data until after
300 * _rtld_init has returned. It is OK to reference file-scope statics
301 * and string constants, and to call static and global functions.
302 */
303 /* Find the auxiliary vector on the stack. */
304 /* first Elf_Word reserved to address of exit routine */
305 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
306 dbg(("sp = %p, argc = %ld, argv = %p <%s>\n", sp, (long)sp[2],
307 &sp[3], (char *) sp[3]));
308 dbg(("got is at %p, dynamic is at %p\n",
309 _GLOBAL_OFFSET_TABLE_, &_DYNAMIC));
310 debug = 1;
311 dbg(("_ctype_ is %p\n", _ctype_));
312 #endif
313
314 sp += 2; /* skip over return argument space */
315 argv = (const char **) &sp[1];
316 argc = *(long *)sp;
317 #ifdef __sparc_v9__
318 /* XXX Temporary hack for argc format conversion. */
319 argc = (argc >> 32) | (argc & 0xffffffff);
320 #endif
321 sp += 2 + argc; /* Skip over argc, arguments, and NULL
322 * terminator */
323 env = (char **) sp;
324 while (*sp++ != 0) { /* Skip over environment, and NULL terminator */
325 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
326 dbg(("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]));
327 #endif
328 }
329 aux = (const AuxInfo *) sp;
330
331 pAUX_base = pAUX_entry = pAUX_execfd = NULL;
332 pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
333 pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
334 #ifdef VARPSZ
335 pAUX_pagesz = NULL;
336 #endif
337 /*
338 * First pass through the the auxiliary vector, avoiding the use
339 * of a `switch() {}' statement at this stage. A `switch()' may
340 * be translated into code utilizing a jump table approach which
341 * references the equivalent of a global variable. This must be
342 * avoided until _rtld_init() has done its job.
343 *
344 * _rtld_init() only needs `pAUX_base' and possibly `pAUX_pagesz',
345 * so we look for just those in this pass.
346 */
347 for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
348 if (auxp->a_type == AT_BASE)
349 pAUX_base = auxp;
350 #ifdef VARPSZ
351 if (auxp->a_type == AT_PAGESZ)
352 pAUX_pagesz = auxp;
353 #endif
354 }
355
356 /* Initialize and relocate ourselves. */
357 assert(pAUX_base != NULL);
358 #ifdef VARPSZ
359 assert(pAUX_pagesz != NULL);
360 _rtld_init((caddr_t) pAUX_base->a_v, (int)pAUX_pagesz->a_v);
361 #else
362 _rtld_init((caddr_t) pAUX_base->a_v, 0);
363 #endif
364
365 /* Digest the auxiliary vector (full pass now that we can afford it). */
366 for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
367 switch (auxp->a_type) {
368 case AT_BASE:
369 pAUX_base = auxp;
370 break;
371 case AT_ENTRY:
372 pAUX_entry = auxp;
373 break;
374 case AT_EXECFD:
375 pAUX_execfd = auxp;
376 break;
377 case AT_PHDR:
378 pAUX_phdr = auxp;
379 break;
380 case AT_PHENT:
381 pAUX_phent = auxp;
382 break;
383 case AT_PHNUM:
384 pAUX_phnum = auxp;
385 break;
386 case AT_EUID:
387 pAUX_euid = auxp;
388 break;
389 case AT_RUID:
390 pAUX_ruid = auxp;
391 break;
392 case AT_EGID:
393 pAUX_egid = auxp;
394 break;
395 case AT_RGID:
396 pAUX_rgid = auxp;
397 break;
398 #ifdef VARPSZ
399 case AT_PAGESZ:
400 pAUX_pagesz = auxp;
401 break;
402 #endif
403 }
404 }
405
406 #ifdef VARPSZ
407 _rtld_pagesz = (int)pAUX_pagesz->a_v;
408 #endif
409
410 #ifdef RTLD_DEBUG
411 dbg(("_ctype_ is %p\n", _ctype_));
412 #endif
413
414 __progname = _rtld_objself.path;
415 environ = env;
416
417 _rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
418 (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
419 ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
420 (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
421
422 ld_bind_now = getenv("LD_BIND_NOW");
423 if (ld_bind_now != NULL && *ld_bind_now != '\0')
424 bind_now = true;
425 if (_rtld_trust) {
426 #ifdef DEBUG
427 const char *ld_debug = getenv("LD_DEBUG");
428 if (ld_debug != NULL && *ld_debug != '\0')
429 debug = 1;
430 #endif
431 _rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
432 }
433 _rtld_process_hints(&_rtld_paths, &_rtld_xforms, _PATH_LD_HINTS, true);
434 dbg(("%s is initialized, base address = %p", __progname,
435 (void *) pAUX_base->a_v));
436
437 /*
438 * Load the main program, or process its program header if it is
439 * already loaded.
440 */
441 if (pAUX_execfd != NULL) { /* Load the main program. */
442 int fd = pAUX_execfd->a_v;
443 dbg(("loading main program"));
444 _rtld_objmain = _rtld_map_object(argv[0], fd, NULL);
445 close(fd);
446 if (_rtld_objmain == NULL)
447 _rtld_die();
448 } else { /* Main program already loaded. */
449 const Elf_Phdr *phdr;
450 int phnum;
451 caddr_t entry;
452
453 dbg(("processing main program's program header"));
454 assert(pAUX_phdr != NULL);
455 phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
456 assert(pAUX_phnum != NULL);
457 phnum = pAUX_phnum->a_v;
458 assert(pAUX_phent != NULL);
459 assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
460 assert(pAUX_entry != NULL);
461 entry = (caddr_t) pAUX_entry->a_v;
462 _rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
463 }
464
465 if (argv[0] != NULL)
466 _rtld_objmain->path = xstrdup(argv[0]);
467 else
468 _rtld_objmain->path = xstrdup("main program");
469 _rtld_objmain->mainprog = true;
470
471 /*
472 * Get the actual dynamic linker pathname from the executable if
473 * possible. (It should always be possible.) That ensures that
474 * gdb will find the right dynamic linker even if a non-standard
475 * one is being used.
476 */
477 if (_rtld_objmain->interp != NULL &&
478 strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
479 free(_rtld_objself.path);
480 _rtld_objself.path = xstrdup(_rtld_objmain->interp);
481 }
482
483 _rtld_digest_dynamic(_rtld_objmain);
484
485 _rtld_linkmap_add(_rtld_objmain);
486 _rtld_linkmap_add(&_rtld_objself);
487
488 /* Link the main program into the list of objects. */
489 *_rtld_objtail = _rtld_objmain;
490 _rtld_objtail = &_rtld_objmain->next;
491 ++_rtld_objmain->refcount;
492
493 /* Initialize a fake symbol for resolving undefined weak references. */
494 _rtld_sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
495 _rtld_sym_zero.st_shndx = SHN_ABS;
496
497 /*
498 * Pre-load user-specified objects after the main program but before
499 * any shared object dependencies.
500 */
501 dbg(("preloading objects"));
502 if (_rtld_trust && _rtld_preload(getenv("LD_PRELOAD"), true) == -1)
503 _rtld_die();
504
505 dbg(("loading needed objects"));
506 if (_rtld_load_needed_objects(_rtld_objmain, RTLD_GLOBAL, true) == -1)
507 _rtld_die();
508
509 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
510 _rtld_objlist_add(&_rtld_list_main, obj);
511
512 dbg(("relocating objects"));
513 if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
514 _rtld_die();
515
516 dbg(("doing copy relocations"));
517 if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
518 _rtld_die();
519
520 /*
521 * Set the __progname, environ and, __mainprog_obj before
522 * calling anything that might use them.
523 */
524 real___progname = _rtld_objmain_sym("__progname");
525 if (real___progname) {
526 if ((*real___progname = strrchr(argv[0], '/')) == NULL)
527 (*real___progname) = argv[0];
528 else
529 (*real___progname)++;
530 }
531 real_environ = _rtld_objmain_sym("environ");
532 if (real_environ)
533 *real_environ = environ;
534 real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
535 if (real___mainprog_obj)
536 *real___mainprog_obj = _rtld_objmain;
537
538 dbg(("calling _init functions"));
539 _rtld_call_init_functions(_rtld_objmain->next);
540
541 dbg(("control at program entry point = %p, obj = %p, exit = %p",
542 _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
543
544 /*
545 * Return with the entry point and the exit procedure in at the top
546 * of stack.
547 */
548
549 _rtld_debug_state(); /* say hello to gdb! */
550
551 ((void **) osp)[0] = _rtld_exit;
552 ((void **) osp)[1] = _rtld_objmain;
553 return (Elf_Addr) _rtld_objmain->entry;
554 }
555
556 void
557 _rtld_die()
558 {
559 const char *msg = _rtld_dlerror();
560
561 if (msg == NULL)
562 msg = "Fatal error";
563 xerrx(1, "%s", msg);
564 }
565
566 static Obj_Entry *
567 _rtld_dlcheck(handle)
568 void *handle;
569 {
570 Obj_Entry *obj;
571
572 for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
573 if (obj == (Obj_Entry *) handle)
574 break;
575
576 if (obj == NULL || obj->dl_refcount == 0) {
577 xwarnx("Invalid shared object handle %p", handle);
578 return NULL;
579 }
580 return obj;
581 }
582
583 static void
584 _rtld_init_dag(root)
585 Obj_Entry *root;
586 {
587 _rtld_curmark++;
588 _rtld_init_dag1(root, root);
589 }
590
591 static void
592 _rtld_init_dag1(root, obj)
593 Obj_Entry *root;
594 Obj_Entry *obj;
595 {
596 const Needed_Entry *needed;
597
598 if (obj->mark == _rtld_curmark)
599 return;
600 obj->mark = _rtld_curmark;
601 _rtld_objlist_add(&obj->dldags, root);
602 _rtld_objlist_add(&root->dagmembers, obj);
603 for (needed = obj->needed; needed != NULL; needed = needed->next)
604 if (needed->obj != NULL)
605 _rtld_init_dag1(root, needed->obj);
606 }
607
608 /*
609 * Note, this is called only for objects loaded by dlopen().
610 */
611 static void
612 _rtld_unload_object(root, do_fini_funcs)
613 Obj_Entry *root;
614 bool do_fini_funcs;
615 {
616 _rtld_unref_dag(root);
617 if (root->refcount == 0) { /* We are finished with some objects. */
618 Obj_Entry *obj;
619 Obj_Entry **linkp;
620 Objlist_Entry *elm;
621
622 /* Finalize objects that are about to be unmapped. */
623 if (do_fini_funcs)
624 for (obj = _rtld_objlist->next; obj != NULL; obj = obj->next)
625 if (obj->refcount == 0 && obj->fini != NULL)
626 (*obj->fini)();
627
628 /* Remove the DAG from all objects' DAG lists. */
629 SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
630 _rtld_objlist_remove(&elm->obj->dldags, root);
631
632 /* Remove the DAG from the RTLD_GLOBAL list. */
633 _rtld_objlist_remove(&_rtld_list_global, root);
634
635 /* Unmap all objects that are no longer referenced. */
636 linkp = &_rtld_objlist->next;
637 while ((obj = *linkp) != NULL) {
638 if (obj->refcount == 0) {
639 #ifdef RTLD_DEBUG
640 dbg(("unloading \"%s\"", obj->path));
641 #endif
642 munmap(obj->mapbase, obj->mapsize);
643 _rtld_objlist_remove(&_rtld_list_global, obj);
644 _rtld_linkmap_delete(obj);
645 *linkp = obj->next;
646 _rtld_obj_free(obj);
647 } else
648 linkp = &obj->next;
649 }
650 _rtld_objtail = linkp;
651 }
652 }
653
654 static void
655 _rtld_unref_dag(root)
656 Obj_Entry *root;
657 {
658 assert(root);
659 assert(root->refcount != 0);
660 --root->refcount;
661 if (root->refcount == 0) {
662 const Needed_Entry *needed;
663
664 for (needed = root->needed; needed != NULL;
665 needed = needed->next) {
666 if (needed->obj != NULL)
667 _rtld_unref_dag(needed->obj);
668 }
669 }
670 }
671
672 int
673 _rtld_dlclose(handle)
674 void *handle;
675 {
676 Obj_Entry *root = _rtld_dlcheck(handle);
677
678 if (root == NULL)
679 return -1;
680
681 _rtld_debug.r_state = RT_DELETE;
682 _rtld_debug_state();
683
684 --root->dl_refcount;
685 _rtld_unload_object(root, true);
686
687 _rtld_debug.r_state = RT_CONSISTENT;
688 _rtld_debug_state();
689
690 return 0;
691 }
692
693 char *
694 _rtld_dlerror()
695 {
696 char *msg = error_message;
697 error_message = NULL;
698 return msg;
699 }
700
701 void *
702 _rtld_dlopen(name, mode)
703 const char *name;
704 int mode;
705 {
706 Obj_Entry **old_obj_tail = _rtld_objtail;
707 Obj_Entry *obj = NULL;
708
709 _rtld_debug.r_state = RT_ADD;
710 _rtld_debug_state();
711
712 if (name == NULL) {
713 obj = _rtld_objmain;
714 obj->refcount++;
715 } else {
716 char *path = _rtld_find_library(name, _rtld_objmain);
717 if (path != NULL)
718 obj = _rtld_load_object(path, mode, true);
719 }
720
721 if (obj != NULL) {
722 ++obj->dl_refcount;
723 if (*old_obj_tail != NULL) { /* We loaded something new. */
724 assert(*old_obj_tail == obj);
725
726 if (_rtld_load_needed_objects(obj, mode, true) == -1 ||
727 (_rtld_init_dag(obj),
728 _rtld_relocate_objects(obj,
729 ((mode & 3) == RTLD_NOW), true)) == -1) {
730 _rtld_unload_object(obj, false);
731 obj->dl_refcount--;
732 obj = NULL;
733 } else
734 _rtld_call_init_functions(obj);
735 }
736 }
737 _rtld_debug.r_state = RT_CONSISTENT;
738 _rtld_debug_state();
739
740 return obj;
741 }
742
743 /*
744 * Find a symbol in the main program.
745 */
746 void *
747 _rtld_objmain_sym(name)
748 const char *name;
749 {
750 unsigned long hash;
751 const Elf_Sym *def;
752 const Obj_Entry *obj;
753
754 hash = _rtld_elf_hash(name);
755 obj = _rtld_objmain;
756
757 _rtld_curmark++;
758 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, true);
759
760 if (def != NULL)
761 return obj->relocbase + def->st_value;
762 return(NULL);
763 }
764
765 void *
766 _rtld_dlsym(handle, name)
767 void *handle;
768 const char *name;
769 {
770 const Obj_Entry *obj;
771 unsigned long hash;
772 const Elf_Sym *def;
773 const Obj_Entry *defobj;
774
775 hash = _rtld_elf_hash(name);
776 def = NULL;
777 defobj = NULL;
778
779 if (handle == NULL
780 #if 0
781 || handle == RTLD_NEXT
782 #endif
783 ) {
784 void *retaddr;
785
786 retaddr = __builtin_return_address(0); /* __GNUC__ only */
787 if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
788 _rtld_error("Cannot determine caller's shared object");
789 return NULL;
790 }
791 if (handle == NULL) { /* Just the caller's shared object. */
792 def = _rtld_symlook_obj(name, hash, obj, true);
793 defobj = obj;
794 } else { /* All the shared objects after the caller's */
795 while ((obj = obj->next) != NULL) {
796 if ((def = _rtld_symlook_obj(name, hash, obj, true)) != NULL) {
797 defobj = obj;
798 break;
799 }
800 }
801 }
802 } else {
803 if ((obj = _rtld_dlcheck(handle)) == NULL)
804 return NULL;
805
806 if (obj->mainprog) {
807 /* Search main program and all libraries loaded by it. */
808 _rtld_curmark++;
809 def = _rtld_symlook_list(name, hash, &_rtld_list_main, &defobj, true);
810 } else {
811 /*
812 * XXX - This isn't correct. The search should include the whole
813 * DAG rooted at the given object.
814 */
815 def = _rtld_symlook_obj(name, hash, obj, true);
816 defobj = obj;
817 }
818 }
819
820 if (def != NULL) {
821 #ifdef __HAVE_FUNCTION_DESCRIPTORS
822 if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
823 return (void *)_rtld_function_descriptor_alloc(defobj,
824 def, 0);
825 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
826 return defobj->relocbase + def->st_value;
827 }
828
829 _rtld_error("Undefined symbol \"%s\"", name);
830 return NULL;
831 }
832
833 int
834 _rtld_dladdr(addr, info)
835 const void *addr;
836 Dl_info *info;
837 {
838 const Obj_Entry *obj;
839 const Elf_Sym *def, *best_def;
840 void *symbol_addr;
841 unsigned long symoffset;
842
843 #ifdef __HAVE_FUNCTION_DESCRIPTORS
844 addr = _rtld_function_descriptor_function(addr);
845 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
846
847 obj = _rtld_obj_from_addr(addr);
848 if (obj == NULL) {
849 _rtld_error("No shared object contains address");
850 return 0;
851 }
852 info->dli_fname = obj->path;
853 info->dli_fbase = obj->mapbase;
854 info->dli_saddr = (void *)0;
855 info->dli_sname = NULL;
856
857 /*
858 * Walk the symbol list looking for the symbol whose address is
859 * closest to the address sent in.
860 */
861 best_def = NULL;
862 for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
863 def = obj->symtab + symoffset;
864
865 /*
866 * For skip the symbol if st_shndx is either SHN_UNDEF or
867 * SHN_COMMON.
868 */
869 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
870 continue;
871
872 /*
873 * If the symbol is greater than the specified address, or if it
874 * is further away from addr than the current nearest symbol,
875 * then reject it.
876 */
877 symbol_addr = obj->relocbase + def->st_value;
878 if (symbol_addr > addr || symbol_addr < info->dli_saddr)
879 continue;
880
881 /* Update our idea of the nearest symbol. */
882 info->dli_sname = obj->strtab + def->st_name;
883 info->dli_saddr = symbol_addr;
884 best_def = def;
885
886 /* Exact match? */
887 if (info->dli_saddr == addr)
888 break;
889 }
890
891 #ifdef __HAVE_FUNCTION_DESCRIPTORS
892 if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
893 info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
894 best_def, 0);
895 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
896
897 return 1;
898 }
899
900 /*
901 * Error reporting function. Use it like printf. If formats the message
902 * into a buffer, and sets things up so that the next call to dlerror()
903 * will return the message.
904 */
905 void
906 _rtld_error(const char *fmt,...)
907 {
908 static char buf[512];
909 va_list ap;
910
911 va_start(ap, fmt);
912 xvsnprintf(buf, sizeof buf, fmt, ap);
913 error_message = buf;
914 va_end(ap);
915 }
916
917 void
918 _rtld_debug_state()
919 {
920 /* do nothing */
921 }
922
923 void
924 _rtld_linkmap_add(obj)
925 Obj_Entry *obj;
926 {
927 struct link_map *l = &obj->linkmap;
928 struct link_map *prev;
929
930 obj->linkmap.l_name = obj->path;
931 obj->linkmap.l_addr = obj->mapbase;
932 obj->linkmap.l_ld = obj->dynamic;
933 #ifdef __mips__
934 /* GDB needs load offset on MIPS to use the symbols */
935 obj->linkmap.l_offs = obj->relocbase;
936 #endif
937 #ifdef __vax__
938 /* VAX shared libaries don't start at a vaddr of 0 */
939 obj->linkmap.l_addr -= obj->vaddrbase;
940 #endif
941
942 if (_rtld_debug.r_map == NULL) {
943 _rtld_debug.r_map = l;
944 return;
945 }
946 for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
947 l->l_prev = prev;
948 prev->l_next = l;
949 l->l_next = NULL;
950 }
951
952 void
953 _rtld_linkmap_delete(obj)
954 Obj_Entry *obj;
955 {
956 struct link_map *l = &obj->linkmap;
957
958 if (l->l_prev == NULL) {
959 if ((_rtld_debug.r_map = l->l_next) != NULL)
960 l->l_next->l_prev = NULL;
961 return;
962 }
963 if ((l->l_prev->l_next = l->l_next) != NULL)
964 l->l_next->l_prev = l->l_prev;
965 }
966
967 static Obj_Entry *
968 _rtld_obj_from_addr(const void *addr)
969 {
970 unsigned long endhash;
971 Obj_Entry *obj;
972
973 endhash = _rtld_elf_hash(END_SYM);
974 for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
975 const Elf_Sym *endsym;
976
977 if (addr < (void *) obj->mapbase)
978 continue;
979 if ((endsym = _rtld_symlook_obj(END_SYM, endhash, obj, true)) == NULL)
980 continue; /* No "end" symbol?! */
981 if (addr < (void *) (obj->relocbase + endsym->st_value))
982 return obj;
983 }
984 return NULL;
985 }
986
987 static void
988 _rtld_objlist_remove(list, obj)
989 Objlist *list;
990 Obj_Entry *obj;
991 {
992 Objlist_Entry *elm;
993
994 if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
995 SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
996 free(elm);
997 }
998 }
999