xref: /netbsd/libexec/ld.elf_so/rtld.c (revision bf9ec67e)
1 /*	$NetBSD: rtld.c,v 1.49 2002/05/26 00:02:07 wiz Exp $	 */
2 
3 /*
4  * Copyright 1996 John D. Polstra.
5  * Copyright 1996 Matt Thomas <matt@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@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;
277 #ifdef	VARPSZ
278 	const AuxInfo  *pAUX_pagesz;
279 #endif
280 	char          **env;
281 	const AuxInfo  *aux;
282 	const AuxInfo  *auxp;
283 	Elf_Addr       *const osp = sp;
284 	bool            bind_now = 0;
285 	const char     *ld_bind_now;
286 	const char    **argv;
287 	long		argc;
288 	Obj_Entry	*obj;
289 	const char **real___progname;
290 	const Obj_Entry **real___mainprog_obj;
291 	char ***real_environ;
292 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
293 	int             i = 0;
294 #endif
295 
296 	/*
297          * On entry, the dynamic linker itself has not been relocated yet.
298          * Be very careful not to reference any global data until after
299          * _rtld_init has returned.  It is OK to reference file-scope statics
300          * and string constants, and to call static and global functions.
301          */
302 	/* Find the auxiliary vector on the stack. */
303 	/* first Elf_Word reserved to address of exit routine */
304 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
305 	dbg(("sp = %p, argc = %ld, argv = %p <%s>\n", sp, (long)sp[2],
306 	     &sp[3], (char *) sp[3]));
307 	dbg(("got is at %p, dynamic is at %p\n",
308 	    _GLOBAL_OFFSET_TABLE_, &_DYNAMIC));
309 	debug = 1;
310 	dbg(("_ctype_ is %p\n", _ctype_));
311 #endif
312 
313 	sp += 2;		/* skip over return argument space */
314 	argv = (const char **) &sp[1];
315 	argc = *(long *)sp;
316 #ifdef __sparc_v9__
317 	/* XXX Temporary hack for argc format conversion. */
318 	argc = (argc >> 32) | (argc & 0xffffffff);
319 #endif
320 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
321 				 * terminator */
322 	env = (char **) sp;
323 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
324 #if defined(RTLD_DEBUG) && !defined(RTLD_RELOCATE_SELF)
325 		dbg(("env[%d] = %p %s\n", i++, (void *)sp[-1], (char *)sp[-1]));
326 #endif
327 	}
328 	aux = (const AuxInfo *) sp;
329 
330 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
331 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
332 #ifdef	VARPSZ
333 	pAUX_pagesz = NULL;
334 #endif
335 	/*
336 	 * First pass through the the auxiliary vector, avoiding the use
337 	 * of a `switch() {}' statement at this stage. A `switch()' may
338 	 * be translated into code utilizing a jump table approach which
339 	 * references the equivalent of a global variable. This must be
340 	 * avoided until _rtld_init() has done its job.
341 	 *
342 	 * _rtld_init() only needs `pAUX_base' and possibly `pAUX_pagesz',
343 	 * so we look for just those in this pass.
344 	 */
345 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
346 		if (auxp->a_type == AT_BASE)
347 			pAUX_base = auxp;
348 #ifdef	VARPSZ
349 		if (auxp->a_type == AT_PAGESZ)
350 			pAUX_pagesz = auxp;
351 #endif
352 	}
353 
354 	/* Initialize and relocate ourselves. */
355 	assert(pAUX_base != NULL);
356 #ifdef	VARPSZ
357 	assert(pAUX_pagesz != NULL);
358 	_rtld_init((caddr_t) pAUX_base->a_v, (int)pAUX_pagesz->a_v);
359 #else
360 	_rtld_init((caddr_t) pAUX_base->a_v, 0);
361 #endif
362 
363 	/* Digest the auxiliary vector (full pass now that we can afford it). */
364 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
365 		switch (auxp->a_type) {
366 		case AT_BASE:
367 			pAUX_base = auxp;
368 			break;
369 		case AT_ENTRY:
370 			pAUX_entry = auxp;
371 			break;
372 		case AT_EXECFD:
373 			pAUX_execfd = auxp;
374 			break;
375 		case AT_PHDR:
376 			pAUX_phdr = auxp;
377 			break;
378 		case AT_PHENT:
379 			pAUX_phent = auxp;
380 			break;
381 		case AT_PHNUM:
382 			pAUX_phnum = auxp;
383 			break;
384 #ifdef	VARPSZ
385 		case AT_PAGESZ:
386 			pAUX_pagesz = auxp;
387 			break;
388 #endif
389 		}
390 	}
391 
392 #ifdef	VARPSZ
393 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
394 #endif
395 
396 #ifdef RTLD_DEBUG
397 	dbg(("_ctype_ is %p\n", _ctype_));
398 #endif
399 
400 	__progname = _rtld_objself.path;
401 	environ = env;
402 
403 	_rtld_trust = geteuid() == getuid() && getegid() == getgid();
404 
405 	ld_bind_now = getenv("LD_BIND_NOW");
406 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
407 		bind_now = true;
408 	if (_rtld_trust) {
409 #ifdef DEBUG
410 		const char     *ld_debug = getenv("LD_DEBUG");
411 		if (ld_debug != NULL && *ld_debug != '\0')
412 			debug = 1;
413 #endif
414 		_rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"), true);
415 	}
416 	_rtld_process_hints(&_rtld_paths, &_rtld_xforms, _PATH_LD_HINTS, true);
417 	dbg(("%s is initialized, base address = %p", __progname,
418 	     (void *) pAUX_base->a_v));
419 
420 	/*
421          * Load the main program, or process its program header if it is
422          * already loaded.
423          */
424 	if (pAUX_execfd != NULL) {	/* Load the main program. */
425 		int             fd = pAUX_execfd->a_v;
426 		dbg(("loading main program"));
427 		_rtld_objmain = _rtld_map_object(argv[0], fd, NULL);
428 		close(fd);
429 		if (_rtld_objmain == NULL)
430 			_rtld_die();
431 	} else {		/* Main program already loaded. */
432 		const Elf_Phdr *phdr;
433 		int             phnum;
434 		caddr_t         entry;
435 
436 		dbg(("processing main program's program header"));
437 		assert(pAUX_phdr != NULL);
438 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
439 		assert(pAUX_phnum != NULL);
440 		phnum = pAUX_phnum->a_v;
441 		assert(pAUX_phent != NULL);
442 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
443 		assert(pAUX_entry != NULL);
444 		entry = (caddr_t) pAUX_entry->a_v;
445 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
446 	}
447 
448 	if (argv[0] != NULL)
449 		_rtld_objmain->path = xstrdup(argv[0]);
450 	else
451 		_rtld_objmain->path = xstrdup("main program");
452 	_rtld_objmain->mainprog = true;
453 
454 	/*
455 	 * Get the actual dynamic linker pathname from the executable if
456 	 * possible.  (It should always be possible.)  That ensures that
457 	 * gdb will find the right dynamic linker even if a non-standard
458 	 * one is being used.
459 	 */
460 	if (_rtld_objmain->interp != NULL &&
461 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
462 		free(_rtld_objself.path);
463 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
464 	}
465 
466 	_rtld_digest_dynamic(_rtld_objmain);
467 
468 	_rtld_linkmap_add(_rtld_objmain);
469 	_rtld_linkmap_add(&_rtld_objself);
470 
471 	/* Link the main program into the list of objects. */
472 	*_rtld_objtail = _rtld_objmain;
473 	_rtld_objtail = &_rtld_objmain->next;
474 	++_rtld_objmain->refcount;
475 
476 	/* Initialize a fake symbol for resolving undefined weak references. */
477 	_rtld_sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
478 	_rtld_sym_zero.st_shndx = SHN_ABS;
479 
480 	/*
481 	 * Pre-load user-specified objects after the main program but before
482 	 * any shared object dependencies.
483 	 */
484 	dbg(("preloading objects"));
485 	if (_rtld_trust && _rtld_preload(getenv("LD_PRELOAD"), true) == -1)
486 		_rtld_die();
487 
488 	dbg(("loading needed objects"));
489 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_GLOBAL, true) == -1)
490 		_rtld_die();
491 
492 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next)
493 		_rtld_objlist_add(&_rtld_list_main, obj);
494 
495 	dbg(("relocating objects"));
496 	if (_rtld_relocate_objects(_rtld_objmain, bind_now, true) == -1)
497 		_rtld_die();
498 
499 	dbg(("doing copy relocations"));
500 	if (_rtld_do_copy_relocations(_rtld_objmain, true) == -1)
501 		_rtld_die();
502 
503 	/*
504 	 * Set the __progname,  environ and, __mainprog_obj before
505 	 * calling anything that might use them.
506 	 */
507 	real___progname = _rtld_objmain_sym("__progname");
508 	if (real___progname) {
509 		if ((*real___progname = strrchr(argv[0], '/')) == NULL)
510 			(*real___progname) = argv[0];
511 		else
512 			(*real___progname)++;
513 	}
514 	real_environ = _rtld_objmain_sym("environ");
515 	if (real_environ)
516 		*real_environ = environ;
517 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
518 	if (real___mainprog_obj)
519 		*real___mainprog_obj = _rtld_objmain;
520 
521 	dbg(("calling _init functions"));
522 	_rtld_call_init_functions(_rtld_objmain->next);
523 
524 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
525 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
526 
527 	/*
528 	 * Return with the entry point and the exit procedure in at the top
529 	 * of stack.
530 	 */
531 
532 	_rtld_debug_state();	/* say hello to gdb! */
533 
534 	((void **) osp)[0] = _rtld_exit;
535 	((void **) osp)[1] = _rtld_objmain;
536 	return (Elf_Addr) _rtld_objmain->entry;
537 }
538 
539 void
540 _rtld_die()
541 {
542 	const char *msg = _rtld_dlerror();
543 
544 	if (msg == NULL)
545 		msg = "Fatal error";
546 	xerrx(1, "%s\n", msg);
547 }
548 
549 static Obj_Entry *
550 _rtld_dlcheck(handle)
551 	void *handle;
552 {
553 	Obj_Entry *obj;
554 
555 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
556 		if (obj == (Obj_Entry *) handle)
557 			break;
558 
559 	if (obj == NULL || obj->dl_refcount == 0) {
560 		xwarnx("Invalid shared object handle %p", handle);
561 		return NULL;
562 	}
563 	return obj;
564 }
565 
566 static void
567 _rtld_init_dag(root)
568 	Obj_Entry *root;
569 {
570 	_rtld_curmark++;
571 	_rtld_init_dag1(root, root);
572 }
573 
574 static void
575 _rtld_init_dag1(root, obj)
576 	Obj_Entry *root;
577 	Obj_Entry *obj;
578 {
579 	const Needed_Entry *needed;
580 
581 	if (obj->mark == _rtld_curmark)
582 		return;
583 	obj->mark = _rtld_curmark;
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 		for (elm = SIMPLEQ_FIRST(&root->dagmembers); elm; elm = SIMPLEQ_NEXT(elm, 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), 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 	_rtld_curmark++;
741 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, true);
742 
743 	if (def != NULL)
744 		return obj->relocbase + def->st_value;
745 	return(NULL);
746 }
747 
748 void *
749 _rtld_dlsym(handle, name)
750 	void *handle;
751 	const char *name;
752 {
753 	const Obj_Entry *obj;
754 	unsigned long hash;
755 	const Elf_Sym *def;
756 	const Obj_Entry *defobj;
757 
758 	hash = _rtld_elf_hash(name);
759 	def = NULL;
760 	defobj = NULL;
761 
762 	if (handle == NULL
763 #if 0
764 	    || handle == RTLD_NEXT
765 #endif
766 	) {
767 		void *retaddr;
768 
769 		retaddr = __builtin_return_address(0); /* __GNUC__ only */
770 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
771 			_rtld_error("Cannot determine caller's shared object");
772 			return NULL;
773 		}
774 		if (handle == NULL) { /* Just the caller's shared object. */
775 			def = _rtld_symlook_obj(name, hash, obj, true);
776 			defobj = obj;
777 		} else { /* All the shared objects after the caller's */
778 			while ((obj = obj->next) != NULL) {
779 				if ((def = _rtld_symlook_obj(name, hash, obj, true)) != NULL) {
780 					defobj = obj;
781 					break;
782 				}
783 			}
784 		}
785 	} else {
786 		if ((obj = _rtld_dlcheck(handle)) == NULL)
787 			return NULL;
788 
789 		if (obj->mainprog) {
790 			/* Search main program and all libraries loaded by it. */
791 			_rtld_curmark++;
792 			def = _rtld_symlook_list(name, hash, &_rtld_list_main, &defobj, true);
793 		} else {
794 			/*
795 			 * XXX - This isn't correct.  The search should include the whole
796 			 * DAG rooted at the given object.
797 			 */
798 			def = _rtld_symlook_obj(name, hash, obj, true);
799 			defobj = obj;
800 		}
801 	}
802 
803 	if (def != NULL)
804 		return defobj->relocbase + def->st_value;
805 
806 	_rtld_error("Undefined symbol \"%s\"", name);
807 	return NULL;
808 }
809 
810 int
811 _rtld_dladdr(addr, info)
812 	const void *addr;
813 	Dl_info *info;
814 {
815 	const Obj_Entry *obj;
816 	const Elf_Sym *def;
817 	void *symbol_addr;
818 	unsigned long symoffset;
819 
820 	obj = _rtld_obj_from_addr(addr);
821 	if (obj == NULL) {
822 		_rtld_error("No shared object contains address");
823 		return 0;
824 	}
825 	info->dli_fname = obj->path;
826 	info->dli_fbase = obj->mapbase;
827 	info->dli_saddr = (void *)0;
828 	info->dli_sname = NULL;
829 
830 	/*
831 	 * Walk the symbol list looking for the symbol whose address is
832 	 * closest to the address sent in.
833 	 */
834 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
835 		def = obj->symtab + symoffset;
836 
837 		/*
838 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
839 		 * SHN_COMMON.
840 		 */
841 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
842 			continue;
843 
844 		/*
845 		 * If the symbol is greater than the specified address, or if it
846 		 * is further away from addr than the current nearest symbol,
847 		 * then reject it.
848 		 */
849 		symbol_addr = obj->relocbase + def->st_value;
850 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
851 			continue;
852 
853 		/* Update our idea of the nearest symbol. */
854 		info->dli_sname = obj->strtab + def->st_name;
855 		info->dli_saddr = symbol_addr;
856 
857 		/* Exact match? */
858 		if (info->dli_saddr == addr)
859 			break;
860 	}
861 	return 1;
862 }
863 
864 /*
865  * Error reporting function.  Use it like printf.  If formats the message
866  * into a buffer, and sets things up so that the next call to dlerror()
867  * will return the message.
868  */
869 void
870 _rtld_error(const char *fmt,...)
871 {
872 	static char     buf[512];
873 	va_list         ap;
874 
875 	va_start(ap, fmt);
876 	xvsnprintf(buf, sizeof buf, fmt, ap);
877 	error_message = buf;
878 	va_end(ap);
879 }
880 
881 void
882 _rtld_debug_state()
883 {
884 	/* do nothing */
885 }
886 
887 void
888 _rtld_linkmap_add(obj)
889 	Obj_Entry *obj;
890 {
891 	struct link_map *l = &obj->linkmap;
892 	struct link_map *prev;
893 
894 	obj->linkmap.l_name = obj->path;
895 	obj->linkmap.l_addr = obj->mapbase;
896 	obj->linkmap.l_ld = obj->dynamic;
897 #ifdef __mips__
898 	/* GDB needs load offset on MIPS to use the symbols */
899 	obj->linkmap.l_offs = obj->relocbase;
900 #endif
901 #ifdef __vax__
902 	/* VAX shared libaries don't start at a vaddr of 0 */
903 	obj->linkmap.l_addr -= obj->vaddrbase;
904 #endif
905 
906 	if (_rtld_debug.r_map == NULL) {
907 		_rtld_debug.r_map = l;
908 		return;
909 	}
910 	for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
911 	l->l_prev = prev;
912 	prev->l_next = l;
913 	l->l_next = NULL;
914 }
915 
916 void
917 _rtld_linkmap_delete(obj)
918 	Obj_Entry *obj;
919 {
920 	struct link_map *l = &obj->linkmap;
921 
922 	if (l->l_prev == NULL) {
923 		if ((_rtld_debug.r_map = l->l_next) != NULL)
924 			l->l_next->l_prev = NULL;
925 		return;
926 	}
927 	if ((l->l_prev->l_next = l->l_next) != NULL)
928 		l->l_next->l_prev = l->l_prev;
929 }
930 
931 static Obj_Entry *
932 _rtld_obj_from_addr(const void *addr)
933 {
934 	unsigned long endhash;
935 	Obj_Entry *obj;
936 
937 	endhash = _rtld_elf_hash(END_SYM);
938 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
939 		const Elf_Sym *endsym;
940 
941 		if (addr < (void *) obj->mapbase)
942 			continue;
943 		if ((endsym = _rtld_symlook_obj(END_SYM, endhash, obj, true)) == NULL)
944 			continue; /* No "end" symbol?! */
945 		if (addr < (void *) (obj->relocbase + endsym->st_value))
946 			return obj;
947 	}
948 	return NULL;
949 }
950 
951 static void
952 _rtld_objlist_remove(list, obj)
953 	Objlist *list;
954 	Obj_Entry *obj;
955 {
956 	Objlist_Entry *elm;
957 
958 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
959 		if ((list)->sqh_first == (elm)) {
960 			SIMPLEQ_REMOVE_HEAD(list, elm, link);
961 		}
962 		else {
963 			struct Struct_Objlist_Entry *curelm = (list)->sqh_first;
964 			while (curelm->link.sqe_next != (elm))
965 				curelm = curelm->link.sqe_next;
966 			if((curelm->link.sqe_next =
967 			    curelm->link.sqe_next->link.sqe_next) == NULL)
968 				(list)->sqh_last = &(curelm)->link.sqe_next;
969 		}
970 		free(elm);
971 	}
972 }
973