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