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