rtld.c revision 85004
1169689Skan/*-
2169689Skan * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3169689Skan * All rights reserved.
4169689Skan *
5169689Skan * Redistribution and use in source and binary forms, with or without
6169689Skan * modification, are permitted provided that the following conditions
7169689Skan * are met:
8169689Skan * 1. Redistributions of source code must retain the above copyright
9169689Skan *    notice, this list of conditions and the following disclaimer.
10169689Skan * 2. Redistributions in binary form must reproduce the above copyright
11169689Skan *    notice, this list of conditions and the following disclaimer in the
12169689Skan *    documentation and/or other materials provided with the distribution.
13169689Skan *
14169689Skan * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15169689Skan * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16169689Skan * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17169689Skan * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18169689Skan * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19169689Skan * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20169689Skan * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21169689Skan * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22169689Skan * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23169689Skan * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24169689Skan *
25169689Skan * $FreeBSD: head/libexec/rtld-elf/rtld.c 85004 2001-10-15 18:48:42Z dfr $
26 */
27
28/*
29 * Dynamic linker for ELF.
30 *
31 * John Polstra <jdp@polstra.com>.
32 */
33
34#ifndef __GNUC__
35#error "GCC is needed to compile this file"
36#endif
37
38#include <sys/param.h>
39#include <sys/mman.h>
40#include <sys/stat.h>
41
42#include <dlfcn.h>
43#include <err.h>
44#include <errno.h>
45#include <fcntl.h>
46#include <stdarg.h>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <unistd.h>
51
52#include "debug.h"
53#include "rtld.h"
54
55#define END_SYM		"_end"
56#define PATH_RTLD	"/usr/libexec/ld-elf.so.1"
57
58/* Types. */
59typedef void (*func_ptr_type)();
60
61/*
62 * This structure provides a reentrant way to keep a list of objects and
63 * check which ones have already been processed in some way.
64 */
65typedef struct Struct_DoneList {
66    const Obj_Entry **objs;		/* Array of object pointers */
67    unsigned int num_alloc;		/* Allocated size of the array */
68    unsigned int num_used;		/* Number of array slots used */
69} DoneList;
70
71/*
72 * Function declarations.
73 */
74static const char *basename(const char *);
75static void die(void);
76static void digest_dynamic(Obj_Entry *);
77static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
78static Obj_Entry *dlcheck(void *);
79static bool donelist_check(DoneList *, const Obj_Entry *);
80static void errmsg_restore(char *);
81static char *errmsg_save(void);
82static char *find_library(const char *, const Obj_Entry *);
83static const char *gethints(void);
84static void init_dag(Obj_Entry *);
85static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *);
86static void init_rtld(caddr_t);
87static void initlist_add_neededs(Needed_Entry *needed, Objlist *list);
88static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail,
89  Objlist *list);
90static bool is_exported(const Elf_Sym *);
91static void linkmap_add(Obj_Entry *);
92static void linkmap_delete(Obj_Entry *);
93static int load_needed_objects(Obj_Entry *);
94static int load_preload_objects(void);
95static Obj_Entry *load_object(char *);
96static void lock_check(void);
97static Obj_Entry *obj_from_addr(const void *);
98static void objlist_call_fini(Objlist *);
99static void objlist_call_init(Objlist *);
100static void objlist_clear(Objlist *);
101static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
102static void objlist_init(Objlist *);
103static void objlist_push_head(Objlist *, Obj_Entry *);
104static void objlist_push_tail(Objlist *, Obj_Entry *);
105static void objlist_remove(Objlist *, Obj_Entry *);
106static void objlist_remove_unref(Objlist *);
107static int relocate_objects(Obj_Entry *, bool);
108static void rtld_exit(void);
109static char *search_library_path(const char *, const char *);
110static void set_program_var(const char *, const void *);
111static const Elf_Sym *symlook_default(const char *, unsigned long hash,
112  const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt);
113static const Elf_Sym *symlook_list(const char *, unsigned long,
114  Objlist *, const Obj_Entry **, bool in_plt, DoneList *);
115static void trace_loaded_objects(Obj_Entry *obj);
116static void unload_object(Obj_Entry *);
117static void unref_dag(Obj_Entry *);
118
119void r_debug_state(struct r_debug*, struct link_map*);
120void xprintf(const char *, ...);
121
122/*
123 * Data declarations.
124 */
125static char *error_message;	/* Message for dlerror(), or NULL */
126struct r_debug r_debug;	/* for GDB; */
127static bool trust;		/* False for setuid and setgid programs */
128static char *ld_bind_now;	/* Environment variable for immediate binding */
129static char *ld_debug;		/* Environment variable for debugging */
130static char *ld_library_path;	/* Environment variable for search path */
131static char *ld_preload;	/* Environment variable for libraries to
132				   load first */
133static char *ld_tracing;	/* Called from ldd to print libs */
134static Obj_Entry *obj_list;	/* Head of linked list of shared objects */
135static Obj_Entry **obj_tail;	/* Link field of last object in list */
136static Obj_Entry *obj_main;	/* The main program shared object */
137static Obj_Entry obj_rtld;	/* The dynamic linker shared object */
138static unsigned int obj_count;	/* Number of objects in obj_list */
139
140static Objlist list_global =	/* Objects dlopened with RTLD_GLOBAL */
141  STAILQ_HEAD_INITIALIZER(list_global);
142static Objlist list_main =	/* Objects loaded at program startup */
143  STAILQ_HEAD_INITIALIZER(list_main);
144static Objlist list_fini =	/* Objects needing fini() calls */
145  STAILQ_HEAD_INITIALIZER(list_fini);
146
147static LockInfo lockinfo;
148
149static Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
150
151#define GDB_STATE(s,m)	r_debug.r_state = s; r_debug_state(&r_debug,m);
152
153extern Elf_Dyn _DYNAMIC;
154#pragma weak _DYNAMIC
155
156/*
157 * These are the functions the dynamic linker exports to application
158 * programs.  They are the only symbols the dynamic linker is willing
159 * to export from itself.
160 */
161static func_ptr_type exports[] = {
162    (func_ptr_type) &_rtld_error,
163    (func_ptr_type) &dlclose,
164    (func_ptr_type) &dlerror,
165    (func_ptr_type) &dlopen,
166    (func_ptr_type) &dlsym,
167    (func_ptr_type) &dladdr,
168    (func_ptr_type) &dllockinit,
169    NULL
170};
171
172/*
173 * Global declarations normally provided by crt1.  The dynamic linker is
174 * not built with crt1, so we have to provide them ourselves.
175 */
176char *__progname;
177char **environ;
178
179/*
180 * Fill in a DoneList with an allocation large enough to hold all of
181 * the currently-loaded objects.  Keep this as a macro since it calls
182 * alloca and we want that to occur within the scope of the caller.
183 */
184#define donelist_init(dlp)					\
185    ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),	\
186    assert((dlp)->objs != NULL),				\
187    (dlp)->num_alloc = obj_count,				\
188    (dlp)->num_used = 0)
189
190static __inline void
191rlock_acquire(void)
192{
193    lockinfo.rlock_acquire(lockinfo.thelock);
194    atomic_incr_int(&lockinfo.rcount);
195    lock_check();
196}
197
198static __inline void
199wlock_acquire(void)
200{
201    lockinfo.wlock_acquire(lockinfo.thelock);
202    atomic_incr_int(&lockinfo.wcount);
203    lock_check();
204}
205
206static __inline void
207rlock_release(void)
208{
209    atomic_decr_int(&lockinfo.rcount);
210    lockinfo.rlock_release(lockinfo.thelock);
211}
212
213static __inline void
214wlock_release(void)
215{
216    atomic_decr_int(&lockinfo.wcount);
217    lockinfo.wlock_release(lockinfo.thelock);
218}
219
220/*
221 * Main entry point for dynamic linking.  The first argument is the
222 * stack pointer.  The stack is expected to be laid out as described
223 * in the SVR4 ABI specification, Intel 386 Processor Supplement.
224 * Specifically, the stack pointer points to a word containing
225 * ARGC.  Following that in the stack is a null-terminated sequence
226 * of pointers to argument strings.  Then comes a null-terminated
227 * sequence of pointers to environment strings.  Finally, there is a
228 * sequence of "auxiliary vector" entries.
229 *
230 * The second argument points to a place to store the dynamic linker's
231 * exit procedure pointer and the third to a place to store the main
232 * program's object.
233 *
234 * The return value is the main program's entry point.
235 */
236func_ptr_type
237_rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
238{
239    Elf_Auxinfo *aux_info[AT_COUNT];
240    int i;
241    int argc;
242    char **argv;
243    char **env;
244    Elf_Auxinfo *aux;
245    Elf_Auxinfo *auxp;
246    const char *argv0;
247    Obj_Entry *obj;
248    Obj_Entry **preload_tail;
249    Objlist initlist;
250
251    /*
252     * On entry, the dynamic linker itself has not been relocated yet.
253     * Be very careful not to reference any global data until after
254     * init_rtld has returned.  It is OK to reference file-scope statics
255     * and string constants, and to call static and global functions.
256     */
257
258    /* Find the auxiliary vector on the stack. */
259    argc = *sp++;
260    argv = (char **) sp;
261    sp += argc + 1;	/* Skip over arguments and NULL terminator */
262    env = (char **) sp;
263    while (*sp++ != 0)	/* Skip over environment, and NULL terminator */
264	;
265    aux = (Elf_Auxinfo *) sp;
266
267    /* Digest the auxiliary vector. */
268    for (i = 0;  i < AT_COUNT;  i++)
269	aux_info[i] = NULL;
270    for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
271	if (auxp->a_type < AT_COUNT)
272	    aux_info[auxp->a_type] = auxp;
273    }
274
275    /* Initialize and relocate ourselves. */
276    assert(aux_info[AT_BASE] != NULL);
277    init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
278
279    __progname = obj_rtld.path;
280    argv0 = argv[0] != NULL ? argv[0] : "(null)";
281    environ = env;
282
283    trust = geteuid() == getuid() && getegid() == getgid();
284
285    ld_bind_now = getenv("LD_BIND_NOW");
286    if (trust) {
287	ld_debug = getenv("LD_DEBUG");
288	ld_library_path = getenv("LD_LIBRARY_PATH");
289	ld_preload = getenv("LD_PRELOAD");
290    }
291    ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
292
293    if (ld_debug != NULL && *ld_debug != '\0')
294	debug = 1;
295    dbg("%s is initialized, base address = %p", __progname,
296	(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
297    dbg("RTLD dynamic = %p", obj_rtld.dynamic);
298    dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
299
300    /*
301     * Load the main program, or process its program header if it is
302     * already loaded.
303     */
304    if (aux_info[AT_EXECFD] != NULL) {	/* Load the main program. */
305	int fd = aux_info[AT_EXECFD]->a_un.a_val;
306	dbg("loading main program");
307	obj_main = map_object(fd, argv0, NULL);
308	close(fd);
309	if (obj_main == NULL)
310	    die();
311    } else {				/* Main program already loaded. */
312	const Elf_Phdr *phdr;
313	int phnum;
314	caddr_t entry;
315
316	dbg("processing main program's program header");
317	assert(aux_info[AT_PHDR] != NULL);
318	phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
319	assert(aux_info[AT_PHNUM] != NULL);
320	phnum = aux_info[AT_PHNUM]->a_un.a_val;
321	assert(aux_info[AT_PHENT] != NULL);
322	assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
323	assert(aux_info[AT_ENTRY] != NULL);
324	entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
325	if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
326	    die();
327    }
328
329    obj_main->path = xstrdup(argv0);
330    obj_main->mainprog = true;
331
332    /*
333     * Get the actual dynamic linker pathname from the executable if
334     * possible.  (It should always be possible.)  That ensures that
335     * gdb will find the right dynamic linker even if a non-standard
336     * one is being used.
337     */
338    if (obj_main->interp != NULL &&
339      strcmp(obj_main->interp, obj_rtld.path) != 0) {
340	free(obj_rtld.path);
341	obj_rtld.path = xstrdup(obj_main->interp);
342    }
343
344    digest_dynamic(obj_main);
345
346    linkmap_add(obj_main);
347    linkmap_add(&obj_rtld);
348
349    /* Link the main program into the list of objects. */
350    *obj_tail = obj_main;
351    obj_tail = &obj_main->next;
352    obj_count++;
353    obj_main->refcount++;
354    /* Make sure we don't call the main program's init and fini functions. */
355    obj_main->init = obj_main->fini = NULL;
356
357    /* Initialize a fake symbol for resolving undefined weak references. */
358    sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
359    sym_zero.st_shndx = SHN_ABS;
360
361    dbg("loading LD_PRELOAD libraries");
362    if (load_preload_objects() == -1)
363	die();
364    preload_tail = obj_tail;
365
366    dbg("loading needed objects");
367    if (load_needed_objects(obj_main) == -1)
368	die();
369
370    /* Make a list of all objects loaded at startup. */
371    for (obj = obj_list;  obj != NULL;  obj = obj->next)
372	objlist_push_tail(&list_main, obj);
373
374    if (ld_tracing) {		/* We're done */
375	trace_loaded_objects(obj_main);
376	exit(0);
377    }
378
379    if (relocate_objects(obj_main,
380	ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
381	die();
382
383    dbg("doing copy relocations");
384    if (do_copy_relocations(obj_main) == -1)
385	die();
386
387    dbg("initializing key program variables");
388    set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
389    set_program_var("environ", env);
390
391    dbg("initializing thread locks");
392    lockdflt_init(&lockinfo);
393    lockinfo.thelock = lockinfo.lock_create(lockinfo.context);
394
395    /* Make a list of init functions to call. */
396    objlist_init(&initlist);
397    initlist_add_objects(obj_list, preload_tail, &initlist);
398
399    r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
400
401    objlist_call_init(&initlist);
402    wlock_acquire();
403    objlist_clear(&initlist);
404    wlock_release();
405
406    dbg("transferring control to program entry point = %p", obj_main->entry);
407
408    /* Return the exit procedure and the program entry point. */
409    *exit_proc = rtld_exit;
410    *objp = obj_main;
411    return (func_ptr_type) obj_main->entry;
412}
413
414Elf_Addr
415_rtld_bind(Obj_Entry *obj, Elf_Word reloff)
416{
417    const Elf_Rel *rel;
418    const Elf_Sym *def;
419    const Obj_Entry *defobj;
420    Elf_Addr *where;
421    Elf_Addr target;
422
423    rlock_acquire();
424    if (obj->pltrel)
425	rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
426    else
427	rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
428
429    where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
430    def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
431    if (def == NULL)
432	die();
433
434    target = (Elf_Addr)(defobj->relocbase + def->st_value);
435
436    dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
437      defobj->strtab + def->st_name, basename(obj->path),
438      (void *)target, basename(defobj->path));
439
440    /*
441     * Write the new contents for the jmpslot. Note that depending on
442     * architecture, the value which we need to return back to the
443     * lazy binding trampoline may or may not be the target
444     * address. The value returned from reloc_jmpslot() is the value
445     * that the trampoline needs.
446     */
447    target = reloc_jmpslot(where, target, defobj);
448    rlock_release();
449    return target;
450}
451
452/*
453 * Error reporting function.  Use it like printf.  If formats the message
454 * into a buffer, and sets things up so that the next call to dlerror()
455 * will return the message.
456 */
457void
458_rtld_error(const char *fmt, ...)
459{
460    static char buf[512];
461    va_list ap;
462
463    va_start(ap, fmt);
464    vsnprintf(buf, sizeof buf, fmt, ap);
465    error_message = buf;
466    va_end(ap);
467}
468
469/*
470 * Return a dynamically-allocated copy of the current error message, if any.
471 */
472static char *
473errmsg_save(void)
474{
475    return error_message == NULL ? NULL : xstrdup(error_message);
476}
477
478/*
479 * Restore the current error message from a copy which was previously saved
480 * by errmsg_save().  The copy is freed.
481 */
482static void
483errmsg_restore(char *saved_msg)
484{
485    if (saved_msg == NULL)
486	error_message = NULL;
487    else {
488	_rtld_error("%s", saved_msg);
489	free(saved_msg);
490    }
491}
492
493static const char *
494basename(const char *name)
495{
496    const char *p = strrchr(name, '/');
497    return p != NULL ? p + 1 : name;
498}
499
500static void
501die(void)
502{
503    const char *msg = dlerror();
504
505    if (msg == NULL)
506	msg = "Fatal error";
507    errx(1, "%s", msg);
508}
509
510/*
511 * Process a shared object's DYNAMIC section, and save the important
512 * information in its Obj_Entry structure.
513 */
514static void
515digest_dynamic(Obj_Entry *obj)
516{
517    const Elf_Dyn *dynp;
518    Needed_Entry **needed_tail = &obj->needed;
519    const Elf_Dyn *dyn_rpath = NULL;
520    int plttype = DT_REL;
521
522    for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
523	switch (dynp->d_tag) {
524
525	case DT_REL:
526	    obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
527	    break;
528
529	case DT_RELSZ:
530	    obj->relsize = dynp->d_un.d_val;
531	    break;
532
533	case DT_RELENT:
534	    assert(dynp->d_un.d_val == sizeof(Elf_Rel));
535	    break;
536
537	case DT_JMPREL:
538	    obj->pltrel = (const Elf_Rel *)
539	      (obj->relocbase + dynp->d_un.d_ptr);
540	    break;
541
542	case DT_PLTRELSZ:
543	    obj->pltrelsize = dynp->d_un.d_val;
544	    break;
545
546	case DT_RELA:
547	    obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
548	    break;
549
550	case DT_RELASZ:
551	    obj->relasize = dynp->d_un.d_val;
552	    break;
553
554	case DT_RELAENT:
555	    assert(dynp->d_un.d_val == sizeof(Elf_Rela));
556	    break;
557
558	case DT_PLTREL:
559	    plttype = dynp->d_un.d_val;
560	    assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
561	    break;
562
563	case DT_SYMTAB:
564	    obj->symtab = (const Elf_Sym *)
565	      (obj->relocbase + dynp->d_un.d_ptr);
566	    break;
567
568	case DT_SYMENT:
569	    assert(dynp->d_un.d_val == sizeof(Elf_Sym));
570	    break;
571
572	case DT_STRTAB:
573	    obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
574	    break;
575
576	case DT_STRSZ:
577	    obj->strsize = dynp->d_un.d_val;
578	    break;
579
580	case DT_HASH:
581	    {
582		const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
583		  (obj->relocbase + dynp->d_un.d_ptr);
584		obj->nbuckets = hashtab[0];
585		obj->nchains = hashtab[1];
586		obj->buckets = hashtab + 2;
587		obj->chains = obj->buckets + obj->nbuckets;
588	    }
589	    break;
590
591	case DT_NEEDED:
592	    if (!obj->rtld) {
593		Needed_Entry *nep = NEW(Needed_Entry);
594		nep->name = dynp->d_un.d_val;
595		nep->obj = NULL;
596		nep->next = NULL;
597
598		*needed_tail = nep;
599		needed_tail = &nep->next;
600	    }
601	    break;
602
603	case DT_PLTGOT:
604	    obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
605	    break;
606
607	case DT_TEXTREL:
608	    obj->textrel = true;
609	    break;
610
611	case DT_SYMBOLIC:
612	    obj->symbolic = true;
613	    break;
614
615	case DT_RPATH:
616	    /*
617	     * We have to wait until later to process this, because we
618	     * might not have gotten the address of the string table yet.
619	     */
620	    dyn_rpath = dynp;
621	    break;
622
623	case DT_SONAME:
624	    /* Not used by the dynamic linker. */
625	    break;
626
627	case DT_INIT:
628	    obj->init = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
629	    break;
630
631	case DT_FINI:
632	    obj->fini = (InitFunc) (obj->relocbase + dynp->d_un.d_ptr);
633	    break;
634
635	case DT_DEBUG:
636	    /* XXX - not implemented yet */
637	    dbg("Filling in DT_DEBUG entry");
638	    ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
639	    break;
640
641	default:
642	    dbg("Ignoring d_tag %d = %#x", dynp->d_tag, dynp->d_tag);
643	    break;
644	}
645    }
646
647    obj->traced = false;
648
649    if (plttype == DT_RELA) {
650	obj->pltrela = (const Elf_Rela *) obj->pltrel;
651	obj->pltrel = NULL;
652	obj->pltrelasize = obj->pltrelsize;
653	obj->pltrelsize = 0;
654    }
655
656    if (dyn_rpath != NULL)
657	obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
658}
659
660/*
661 * Process a shared object's program header.  This is used only for the
662 * main program, when the kernel has already loaded the main program
663 * into memory before calling the dynamic linker.  It creates and
664 * returns an Obj_Entry structure.
665 */
666static Obj_Entry *
667digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
668{
669    Obj_Entry *obj;
670    const Elf_Phdr *phlimit = phdr + phnum;
671    const Elf_Phdr *ph;
672    int nsegs = 0;
673
674    obj = obj_new();
675    for (ph = phdr;  ph < phlimit;  ph++) {
676	switch (ph->p_type) {
677
678	case PT_PHDR:
679	    if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
680		_rtld_error("%s: invalid PT_PHDR", path);
681		return NULL;
682	    }
683	    obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
684	    obj->phsize = ph->p_memsz;
685	    break;
686
687	case PT_INTERP:
688	    obj->interp = (const char *) ph->p_vaddr;
689	    break;
690
691	case PT_LOAD:
692	    if (nsegs >= 2) {
693		_rtld_error("%s: too many PT_LOAD segments", path);
694		return NULL;
695	    }
696	    if (nsegs == 0) {	/* First load segment */
697		obj->vaddrbase = trunc_page(ph->p_vaddr);
698		obj->mapbase = (caddr_t) obj->vaddrbase;
699		obj->relocbase = obj->mapbase - obj->vaddrbase;
700		obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
701		  obj->vaddrbase;
702	    } else {		/* Last load segment */
703		obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
704		  obj->vaddrbase;
705	    }
706	    nsegs++;
707	    break;
708
709	case PT_DYNAMIC:
710	    obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
711	    break;
712	}
713    }
714    if (nsegs < 2) {
715	_rtld_error("%s: too few PT_LOAD segments", path);
716	return NULL;
717    }
718
719    obj->entry = entry;
720    return obj;
721}
722
723static Obj_Entry *
724dlcheck(void *handle)
725{
726    Obj_Entry *obj;
727
728    for (obj = obj_list;  obj != NULL;  obj = obj->next)
729	if (obj == (Obj_Entry *) handle)
730	    break;
731
732    if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
733	_rtld_error("Invalid shared object handle %p", handle);
734	return NULL;
735    }
736    return obj;
737}
738
739/*
740 * If the given object is already in the donelist, return true.  Otherwise
741 * add the object to the list and return false.
742 */
743static bool
744donelist_check(DoneList *dlp, const Obj_Entry *obj)
745{
746    unsigned int i;
747
748    for (i = 0;  i < dlp->num_used;  i++)
749	if (dlp->objs[i] == obj)
750	    return true;
751    /*
752     * Our donelist allocation should always be sufficient.  But if
753     * our threads locking isn't working properly, more shared objects
754     * could have been loaded since we allocated the list.  That should
755     * never happen, but we'll handle it properly just in case it does.
756     */
757    if (dlp->num_used < dlp->num_alloc)
758	dlp->objs[dlp->num_used++] = obj;
759    return false;
760}
761
762/*
763 * Hash function for symbol table lookup.  Don't even think about changing
764 * this.  It is specified by the System V ABI.
765 */
766unsigned long
767elf_hash(const char *name)
768{
769    const unsigned char *p = (const unsigned char *) name;
770    unsigned long h = 0;
771    unsigned long g;
772
773    while (*p != '\0') {
774	h = (h << 4) + *p++;
775	if ((g = h & 0xf0000000) != 0)
776	    h ^= g >> 24;
777	h &= ~g;
778    }
779    return h;
780}
781
782/*
783 * Find the library with the given name, and return its full pathname.
784 * The returned string is dynamically allocated.  Generates an error
785 * message and returns NULL if the library cannot be found.
786 *
787 * If the second argument is non-NULL, then it refers to an already-
788 * loaded shared object, whose library search path will be searched.
789 *
790 * The search order is:
791 *   rpath in the referencing file
792 *   LD_LIBRARY_PATH
793 *   ldconfig hints
794 *   /usr/lib
795 */
796static char *
797find_library(const char *name, const Obj_Entry *refobj)
798{
799    char *pathname;
800
801    if (strchr(name, '/') != NULL) {	/* Hard coded pathname */
802	if (name[0] != '/' && !trust) {
803	    _rtld_error("Absolute pathname required for shared object \"%s\"",
804	      name);
805	    return NULL;
806	}
807	return xstrdup(name);
808    }
809
810    dbg(" Searching for \"%s\"", name);
811
812    if ((refobj != NULL &&
813      (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
814      (pathname = search_library_path(name, ld_library_path)) != NULL ||
815      (pathname = search_library_path(name, gethints())) != NULL ||
816      (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
817	return pathname;
818
819    _rtld_error("Shared object \"%s\" not found", name);
820    return NULL;
821}
822
823/*
824 * Given a symbol number in a referencing object, find the corresponding
825 * definition of the symbol.  Returns a pointer to the symbol, or NULL if
826 * no definition was found.  Returns a pointer to the Obj_Entry of the
827 * defining object via the reference parameter DEFOBJ_OUT.
828 */
829const Elf_Sym *
830find_symdef(unsigned long symnum, const Obj_Entry *refobj,
831    const Obj_Entry **defobj_out, bool in_plt, SymCache *cache)
832{
833    const Elf_Sym *ref;
834    const Elf_Sym *def;
835    const Obj_Entry *defobj;
836    const char *name;
837    unsigned long hash;
838
839    /*
840     * If we have already found this symbol, get the information from
841     * the cache.
842     */
843    if (symnum >= refobj->nchains)
844	return NULL;	/* Bad object */
845    if (cache != NULL && cache[symnum].sym != NULL) {
846	*defobj_out = cache[symnum].obj;
847	return cache[symnum].sym;
848    }
849
850    ref = refobj->symtab + symnum;
851    name = refobj->strtab + ref->st_name;
852    hash = elf_hash(name);
853    defobj = NULL;
854
855    def = symlook_default(name, hash, refobj, &defobj, in_plt);
856
857    /*
858     * If we found no definition and the reference is weak, treat the
859     * symbol as having the value zero.
860     */
861    if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
862	def = &sym_zero;
863	defobj = obj_main;
864    }
865
866    if (def != NULL) {
867	*defobj_out = defobj;
868	/* Record the information in the cache to avoid subsequent lookups. */
869	if (cache != NULL) {
870	    cache[symnum].sym = def;
871	    cache[symnum].obj = defobj;
872	}
873    } else {
874	if (refobj != &obj_rtld)
875	    _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
876    }
877    return def;
878}
879
880/*
881 * Return the search path from the ldconfig hints file, reading it if
882 * necessary.  Returns NULL if there are problems with the hints file,
883 * or if the search path there is empty.
884 */
885static const char *
886gethints(void)
887{
888    static char *hints;
889
890    if (hints == NULL) {
891	int fd;
892	struct elfhints_hdr hdr;
893	char *p;
894
895	/* Keep from trying again in case the hints file is bad. */
896	hints = "";
897
898	if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
899	    return NULL;
900	if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
901	  hdr.magic != ELFHINTS_MAGIC ||
902	  hdr.version != 1) {
903	    close(fd);
904	    return NULL;
905	}
906	p = xmalloc(hdr.dirlistlen + 1);
907	if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
908	  read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
909	    free(p);
910	    close(fd);
911	    return NULL;
912	}
913	hints = p;
914	close(fd);
915    }
916    return hints[0] != '\0' ? hints : NULL;
917}
918
919static void
920init_dag(Obj_Entry *root)
921{
922    DoneList donelist;
923
924    donelist_init(&donelist);
925    init_dag1(root, root, &donelist);
926}
927
928static void
929init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
930{
931    const Needed_Entry *needed;
932
933    if (donelist_check(dlp, obj))
934	return;
935    objlist_push_tail(&obj->dldags, root);
936    objlist_push_tail(&root->dagmembers, obj);
937    for (needed = obj->needed;  needed != NULL;  needed = needed->next)
938	if (needed->obj != NULL)
939	    init_dag1(root, needed->obj, dlp);
940}
941
942/*
943 * Initialize the dynamic linker.  The argument is the address at which
944 * the dynamic linker has been mapped into memory.  The primary task of
945 * this function is to relocate the dynamic linker.
946 */
947static void
948init_rtld(caddr_t mapbase)
949{
950    /*
951     * Conjure up an Obj_Entry structure for the dynamic linker.
952     *
953     * The "path" member is supposed to be dynamically-allocated, but we
954     * aren't yet initialized sufficiently to do that.  Below we will
955     * replace the static version with a dynamically-allocated copy.
956     */
957    obj_rtld.path = PATH_RTLD;
958    obj_rtld.rtld = true;
959    obj_rtld.mapbase = mapbase;
960#ifdef PIC
961    obj_rtld.relocbase = mapbase;
962#endif
963    if (&_DYNAMIC != 0) {
964	obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
965	digest_dynamic(&obj_rtld);
966	assert(obj_rtld.needed == NULL);
967	assert(!obj_rtld.textrel);
968
969	/*
970	 * Temporarily put the dynamic linker entry into the object list, so
971	 * that symbols can be found.
972	 */
973	obj_list = &obj_rtld;
974	obj_tail = &obj_rtld.next;
975	obj_count = 1;
976
977	relocate_objects(&obj_rtld, true);
978    }
979
980    /* Make the object list empty again. */
981    obj_list = NULL;
982    obj_tail = &obj_list;
983    obj_count = 0;
984
985    /* Replace the path with a dynamically allocated copy. */
986    obj_rtld.path = xstrdup(obj_rtld.path);
987
988    r_debug.r_brk = r_debug_state;
989    r_debug.r_state = RT_CONSISTENT;
990}
991
992/*
993 * Add the init functions from a needed object list (and its recursive
994 * needed objects) to "list".  This is not used directly; it is a helper
995 * function for initlist_add_objects().  The write lock must be held
996 * when this function is called.
997 */
998static void
999initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1000{
1001    /* Recursively process the successor needed objects. */
1002    if (needed->next != NULL)
1003	initlist_add_neededs(needed->next, list);
1004
1005    /* Process the current needed object. */
1006    if (needed->obj != NULL)
1007	initlist_add_objects(needed->obj, &needed->obj->next, list);
1008}
1009
1010/*
1011 * Scan all of the DAGs rooted in the range of objects from "obj" to
1012 * "tail" and add their init functions to "list".  This recurses over
1013 * the DAGs and ensure the proper init ordering such that each object's
1014 * needed libraries are initialized before the object itself.  At the
1015 * same time, this function adds the objects to the global finalization
1016 * list "list_fini" in the opposite order.  The write lock must be
1017 * held when this function is called.
1018 */
1019static void
1020initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1021{
1022    if (obj->init_done)
1023	return;
1024    obj->init_done = true;
1025
1026    /* Recursively process the successor objects. */
1027    if (&obj->next != tail)
1028	initlist_add_objects(obj->next, tail, list);
1029
1030    /* Recursively process the needed objects. */
1031    if (obj->needed != NULL)
1032	initlist_add_neededs(obj->needed, list);
1033
1034    /* Add the object to the init list. */
1035    if (obj->init != NULL)
1036	objlist_push_tail(list, obj);
1037
1038    /* Add the object to the global fini list in the reverse order. */
1039    if (obj->fini != NULL)
1040	objlist_push_head(&list_fini, obj);
1041}
1042
1043#ifndef FPTR_TARGET
1044#define FPTR_TARGET(f)	((Elf_Addr) (f))
1045#endif
1046
1047static bool
1048is_exported(const Elf_Sym *def)
1049{
1050    Elf_Addr value;
1051    const func_ptr_type *p;
1052
1053    value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1054    for (p = exports;  *p != NULL;  p++)
1055	if (FPTR_TARGET(*p) == value)
1056	    return true;
1057    return false;
1058}
1059
1060/*
1061 * Given a shared object, traverse its list of needed objects, and load
1062 * each of them.  Returns 0 on success.  Generates an error message and
1063 * returns -1 on failure.
1064 */
1065static int
1066load_needed_objects(Obj_Entry *first)
1067{
1068    Obj_Entry *obj;
1069
1070    for (obj = first;  obj != NULL;  obj = obj->next) {
1071	Needed_Entry *needed;
1072
1073	for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
1074	    const char *name = obj->strtab + needed->name;
1075	    char *path = find_library(name, obj);
1076
1077	    needed->obj = NULL;
1078	    if (path == NULL && !ld_tracing)
1079		return -1;
1080
1081	    if (path) {
1082		needed->obj = load_object(path);
1083		if (needed->obj == NULL && !ld_tracing)
1084		    return -1;		/* XXX - cleanup */
1085	    }
1086	}
1087    }
1088
1089    return 0;
1090}
1091
1092static int
1093load_preload_objects(void)
1094{
1095    char *p = ld_preload;
1096    static const char delim[] = " \t:;";
1097
1098    if (p == NULL)
1099	return NULL;
1100
1101    p += strspn(p, delim);
1102    while (*p != '\0') {
1103	size_t len = strcspn(p, delim);
1104	char *path;
1105	char savech;
1106
1107	savech = p[len];
1108	p[len] = '\0';
1109	if ((path = find_library(p, NULL)) == NULL)
1110	    return -1;
1111	if (load_object(path) == NULL)
1112	    return -1;	/* XXX - cleanup */
1113	p[len] = savech;
1114	p += len;
1115	p += strspn(p, delim);
1116    }
1117    return 0;
1118}
1119
1120/*
1121 * Load a shared object into memory, if it is not already loaded.  The
1122 * argument must be a string allocated on the heap.  This function assumes
1123 * responsibility for freeing it when necessary.
1124 *
1125 * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1126 * on failure.
1127 */
1128static Obj_Entry *
1129load_object(char *path)
1130{
1131    Obj_Entry *obj;
1132    int fd = -1;
1133    struct stat sb;
1134
1135    for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1136	if (strcmp(obj->path, path) == 0)
1137	    break;
1138
1139    /*
1140     * If we didn't find a match by pathname, open the file and check
1141     * again by device and inode.  This avoids false mismatches caused
1142     * by multiple links or ".." in pathnames.
1143     *
1144     * To avoid a race, we open the file and use fstat() rather than
1145     * using stat().
1146     */
1147    if (obj == NULL) {
1148	if ((fd = open(path, O_RDONLY)) == -1) {
1149	    _rtld_error("Cannot open \"%s\"", path);
1150	    return NULL;
1151	}
1152	if (fstat(fd, &sb) == -1) {
1153	    _rtld_error("Cannot fstat \"%s\"", path);
1154	    close(fd);
1155	    return NULL;
1156	}
1157	for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1158	    if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1159		close(fd);
1160		break;
1161	    }
1162	}
1163    }
1164
1165    if (obj == NULL) {	/* First use of this object, so we must map it in */
1166	dbg("loading \"%s\"", path);
1167	obj = map_object(fd, path, &sb);
1168	close(fd);
1169	if (obj == NULL) {
1170	    free(path);
1171	    return NULL;
1172	}
1173
1174	obj->path = path;
1175	digest_dynamic(obj);
1176
1177	*obj_tail = obj;
1178	obj_tail = &obj->next;
1179	obj_count++;
1180	linkmap_add(obj);	/* for GDB */
1181
1182	dbg("  %p .. %p: %s", obj->mapbase,
1183	  obj->mapbase + obj->mapsize - 1, obj->path);
1184	if (obj->textrel)
1185	    dbg("  WARNING: %s has impure text", obj->path);
1186    } else
1187	free(path);
1188
1189    obj->refcount++;
1190    return obj;
1191}
1192
1193/*
1194 * Check for locking violations and die if one is found.
1195 */
1196static void
1197lock_check(void)
1198{
1199    int rcount, wcount;
1200
1201    rcount = lockinfo.rcount;
1202    wcount = lockinfo.wcount;
1203    assert(rcount >= 0);
1204    assert(wcount >= 0);
1205    if (wcount > 1 || (wcount != 0 && rcount != 0)) {
1206	_rtld_error("Application locking error: %d readers and %d writers"
1207	  " in dynamic linker.  See DLLOCKINIT(3) in manual pages.",
1208	  rcount, wcount);
1209	die();
1210    }
1211}
1212
1213static Obj_Entry *
1214obj_from_addr(const void *addr)
1215{
1216    unsigned long endhash;
1217    Obj_Entry *obj;
1218
1219    endhash = elf_hash(END_SYM);
1220    for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1221	const Elf_Sym *endsym;
1222
1223	if (addr < (void *) obj->mapbase)
1224	    continue;
1225	if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
1226	    continue;	/* No "end" symbol?! */
1227	if (addr < (void *) (obj->relocbase + endsym->st_value))
1228	    return obj;
1229    }
1230    return NULL;
1231}
1232
1233/*
1234 * Call the finalization functions for each of the objects in "list"
1235 * which are unreferenced.  All of the objects are expected to have
1236 * non-NULL fini functions.
1237 */
1238static void
1239objlist_call_fini(Objlist *list)
1240{
1241    Objlist_Entry *elm;
1242    char *saved_msg;
1243
1244    /*
1245     * Preserve the current error message since a fini function might
1246     * call into the dynamic linker and overwrite it.
1247     */
1248    saved_msg = errmsg_save();
1249    STAILQ_FOREACH(elm, list, link) {
1250	if (elm->obj->refcount == 0) {
1251	    dbg("calling fini function for %s", elm->obj->path);
1252	    (*elm->obj->fini)();
1253	}
1254    }
1255    errmsg_restore(saved_msg);
1256}
1257
1258/*
1259 * Call the initialization functions for each of the objects in
1260 * "list".  All of the objects are expected to have non-NULL init
1261 * functions.
1262 */
1263static void
1264objlist_call_init(Objlist *list)
1265{
1266    Objlist_Entry *elm;
1267    char *saved_msg;
1268
1269    /*
1270     * Preserve the current error message since an init function might
1271     * call into the dynamic linker and overwrite it.
1272     */
1273    saved_msg = errmsg_save();
1274    STAILQ_FOREACH(elm, list, link) {
1275	dbg("calling init function for %s", elm->obj->path);
1276	(*elm->obj->init)();
1277    }
1278    errmsg_restore(saved_msg);
1279}
1280
1281static void
1282objlist_clear(Objlist *list)
1283{
1284    Objlist_Entry *elm;
1285
1286    while (!STAILQ_EMPTY(list)) {
1287	elm = STAILQ_FIRST(list);
1288	STAILQ_REMOVE_HEAD(list, link);
1289	free(elm);
1290    }
1291}
1292
1293static Objlist_Entry *
1294objlist_find(Objlist *list, const Obj_Entry *obj)
1295{
1296    Objlist_Entry *elm;
1297
1298    STAILQ_FOREACH(elm, list, link)
1299	if (elm->obj == obj)
1300	    return elm;
1301    return NULL;
1302}
1303
1304static void
1305objlist_init(Objlist *list)
1306{
1307    STAILQ_INIT(list);
1308}
1309
1310static void
1311objlist_push_head(Objlist *list, Obj_Entry *obj)
1312{
1313    Objlist_Entry *elm;
1314
1315    elm = NEW(Objlist_Entry);
1316    elm->obj = obj;
1317    STAILQ_INSERT_HEAD(list, elm, link);
1318}
1319
1320static void
1321objlist_push_tail(Objlist *list, Obj_Entry *obj)
1322{
1323    Objlist_Entry *elm;
1324
1325    elm = NEW(Objlist_Entry);
1326    elm->obj = obj;
1327    STAILQ_INSERT_TAIL(list, elm, link);
1328}
1329
1330static void
1331objlist_remove(Objlist *list, Obj_Entry *obj)
1332{
1333    Objlist_Entry *elm;
1334
1335    if ((elm = objlist_find(list, obj)) != NULL) {
1336	STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1337	free(elm);
1338    }
1339}
1340
1341/*
1342 * Remove all of the unreferenced objects from "list".
1343 */
1344static void
1345objlist_remove_unref(Objlist *list)
1346{
1347    Objlist newlist;
1348    Objlist_Entry *elm;
1349
1350    STAILQ_INIT(&newlist);
1351    while (!STAILQ_EMPTY(list)) {
1352	elm = STAILQ_FIRST(list);
1353	STAILQ_REMOVE_HEAD(list, link);
1354	if (elm->obj->refcount == 0)
1355	    free(elm);
1356	else
1357	    STAILQ_INSERT_TAIL(&newlist, elm, link);
1358    }
1359    *list = newlist;
1360}
1361
1362/*
1363 * Relocate newly-loaded shared objects.  The argument is a pointer to
1364 * the Obj_Entry for the first such object.  All objects from the first
1365 * to the end of the list of objects are relocated.  Returns 0 on success,
1366 * or -1 on failure.
1367 */
1368static int
1369relocate_objects(Obj_Entry *first, bool bind_now)
1370{
1371    Obj_Entry *obj;
1372
1373    for (obj = first;  obj != NULL;  obj = obj->next) {
1374	if (obj != &obj_rtld)
1375	    dbg("relocating \"%s\"", obj->path);
1376	if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1377	    obj->symtab == NULL || obj->strtab == NULL) {
1378	    _rtld_error("%s: Shared object has no run-time symbol table",
1379	      obj->path);
1380	    return -1;
1381	}
1382
1383	if (obj->textrel) {
1384	    /* There are relocations to the write-protected text segment. */
1385	    if (mprotect(obj->mapbase, obj->textsize,
1386	      PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1387		_rtld_error("%s: Cannot write-enable text segment: %s",
1388		  obj->path, strerror(errno));
1389		return -1;
1390	    }
1391	}
1392
1393	/* Process the non-PLT relocations. */
1394	if (reloc_non_plt(obj, &obj_rtld))
1395		return -1;
1396
1397	if (obj->textrel) {	/* Re-protected the text segment. */
1398	    if (mprotect(obj->mapbase, obj->textsize,
1399	      PROT_READ|PROT_EXEC) == -1) {
1400		_rtld_error("%s: Cannot write-protect text segment: %s",
1401		  obj->path, strerror(errno));
1402		return -1;
1403	    }
1404	}
1405
1406	/* Process the PLT relocations. */
1407	if (reloc_plt(obj) == -1)
1408	    return -1;
1409	/* Relocate the jump slots if we are doing immediate binding. */
1410	if (bind_now)
1411	    if (reloc_jmpslots(obj) == -1)
1412		return -1;
1413
1414
1415	/*
1416	 * Set up the magic number and version in the Obj_Entry.  These
1417	 * were checked in the crt1.o from the original ElfKit, so we
1418	 * set them for backward compatibility.
1419	 */
1420	obj->magic = RTLD_MAGIC;
1421	obj->version = RTLD_VERSION;
1422
1423	/* Set the special PLT or GOT entries. */
1424	init_pltgot(obj);
1425    }
1426
1427    return 0;
1428}
1429
1430/*
1431 * Cleanup procedure.  It will be called (by the atexit mechanism) just
1432 * before the process exits.
1433 */
1434static void
1435rtld_exit(void)
1436{
1437    Obj_Entry *obj;
1438
1439    dbg("rtld_exit()");
1440    wlock_acquire();
1441    /* Clear all the reference counts so the fini functions will be called. */
1442    for (obj = obj_list;  obj != NULL;  obj = obj->next)
1443	obj->refcount = 0;
1444    wlock_release();
1445    objlist_call_fini(&list_fini);
1446    /* No need to remove the items from the list, since we are exiting. */
1447}
1448
1449static char *
1450search_library_path(const char *name, const char *path)
1451{
1452    size_t namelen = strlen(name);
1453    const char *p = path;
1454
1455    if (p == NULL)
1456	return NULL;
1457
1458    p += strspn(p, ":;");
1459    while (*p != '\0') {
1460	size_t len = strcspn(p, ":;");
1461
1462	if (*p == '/' || trust) {
1463	    char *pathname;
1464	    const char *dir = p;
1465	    size_t dirlen = len;
1466
1467	    pathname = xmalloc(dirlen + 1 + namelen + 1);
1468	    strncpy(pathname, dir, dirlen);
1469	    pathname[dirlen] = '/';
1470	    strcpy(pathname + dirlen + 1, name);
1471
1472	    dbg("  Trying \"%s\"", pathname);
1473	    if (access(pathname, F_OK) == 0)		/* We found it */
1474		return pathname;
1475
1476	    free(pathname);
1477	}
1478	p += len;
1479	p += strspn(p, ":;");
1480    }
1481
1482    return NULL;
1483}
1484
1485int
1486dlclose(void *handle)
1487{
1488    Obj_Entry *root;
1489
1490    wlock_acquire();
1491    root = dlcheck(handle);
1492    if (root == NULL) {
1493	wlock_release();
1494	return -1;
1495    }
1496
1497    /* Unreference the object and its dependencies. */
1498    root->dl_refcount--;
1499    unref_dag(root);
1500
1501    if (root->refcount == 0) {
1502	/*
1503	 * The object is no longer referenced, so we must unload it.
1504	 * First, call the fini functions with no locks held.
1505	 */
1506	wlock_release();
1507	objlist_call_fini(&list_fini);
1508	wlock_acquire();
1509	objlist_remove_unref(&list_fini);
1510
1511	/* Finish cleaning up the newly-unreferenced objects. */
1512	GDB_STATE(RT_DELETE,&root->linkmap);
1513	unload_object(root);
1514	GDB_STATE(RT_CONSISTENT,NULL);
1515    }
1516    wlock_release();
1517    return 0;
1518}
1519
1520const char *
1521dlerror(void)
1522{
1523    char *msg = error_message;
1524    error_message = NULL;
1525    return msg;
1526}
1527
1528/*
1529 * This function is deprecated and has no effect.
1530 */
1531void
1532dllockinit(void *context,
1533	   void *(*lock_create)(void *context),
1534           void (*rlock_acquire)(void *lock),
1535           void (*wlock_acquire)(void *lock),
1536           void (*lock_release)(void *lock),
1537           void (*lock_destroy)(void *lock),
1538	   void (*context_destroy)(void *context))
1539{
1540    static void *cur_context;
1541    static void (*cur_context_destroy)(void *);
1542
1543    /* Just destroy the context from the previous call, if necessary. */
1544    if (cur_context_destroy != NULL)
1545	cur_context_destroy(cur_context);
1546    cur_context = context;
1547    cur_context_destroy = context_destroy;
1548}
1549
1550void *
1551dlopen(const char *name, int mode)
1552{
1553    Obj_Entry **old_obj_tail;
1554    Obj_Entry *obj;
1555    Objlist initlist;
1556
1557    objlist_init(&initlist);
1558
1559    wlock_acquire();
1560    GDB_STATE(RT_ADD,NULL);
1561
1562    old_obj_tail = obj_tail;
1563    obj = NULL;
1564    if (name == NULL) {
1565	obj = obj_main;
1566	obj->refcount++;
1567    } else {
1568	char *path = find_library(name, obj_main);
1569	if (path != NULL)
1570	    obj = load_object(path);
1571    }
1572
1573    if (obj) {
1574	obj->dl_refcount++;
1575	if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1576	    objlist_push_tail(&list_global, obj);
1577	mode &= RTLD_MODEMASK;
1578	if (*old_obj_tail != NULL) {		/* We loaded something new. */
1579	    assert(*old_obj_tail == obj);
1580
1581	    if (load_needed_objects(obj) == -1 ||
1582	      (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW)) == -1) {
1583		obj->dl_refcount--;
1584		unref_dag(obj);
1585		if (obj->refcount == 0)
1586		    unload_object(obj);
1587		obj = NULL;
1588	    } else {
1589		/* Make list of init functions to call. */
1590		initlist_add_objects(obj, &obj->next, &initlist);
1591	    }
1592	}
1593    }
1594
1595    GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1596
1597    /* Call the init functions with no locks held. */
1598    wlock_release();
1599    objlist_call_init(&initlist);
1600    wlock_acquire();
1601    objlist_clear(&initlist);
1602    wlock_release();
1603    return obj;
1604}
1605
1606void *
1607dlsym(void *handle, const char *name)
1608{
1609    const Obj_Entry *obj;
1610    unsigned long hash;
1611    const Elf_Sym *def;
1612    const Obj_Entry *defobj;
1613
1614    hash = elf_hash(name);
1615    def = NULL;
1616    defobj = NULL;
1617
1618    rlock_acquire();
1619    if (handle == NULL || handle == RTLD_NEXT || handle == RTLD_DEFAULT) {
1620	void *retaddr;
1621
1622	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
1623	if ((obj = obj_from_addr(retaddr)) == NULL) {
1624	    _rtld_error("Cannot determine caller's shared object");
1625	    rlock_release();
1626	    return NULL;
1627	}
1628	if (handle == NULL) {	/* Just the caller's shared object. */
1629	    def = symlook_obj(name, hash, obj, true);
1630	    defobj = obj;
1631	} else if (handle == RTLD_NEXT) {	/* Objects after caller's */
1632	    while ((obj = obj->next) != NULL) {
1633		if ((def = symlook_obj(name, hash, obj, true)) != NULL) {
1634		    defobj = obj;
1635		    break;
1636		}
1637	    }
1638	} else {
1639	    assert(handle == RTLD_DEFAULT);
1640	    def = symlook_default(name, hash, obj, &defobj, true);
1641	}
1642    } else {
1643	if ((obj = dlcheck(handle)) == NULL) {
1644	    rlock_release();
1645	    return NULL;
1646	}
1647
1648	if (obj->mainprog) {
1649	    DoneList donelist;
1650
1651	    /* Search main program and all libraries loaded by it. */
1652	    donelist_init(&donelist);
1653	    def = symlook_list(name, hash, &list_main, &defobj, true,
1654	      &donelist);
1655	} else {
1656	    /*
1657	     * XXX - This isn't correct.  The search should include the whole
1658	     * DAG rooted at the given object.
1659	     */
1660	    def = symlook_obj(name, hash, obj, true);
1661	    defobj = obj;
1662	}
1663    }
1664
1665    if (def != NULL) {
1666	rlock_release();
1667
1668	/*
1669	 * The value required by the caller is derived from the value
1670	 * of the symbol. For the ia64 architecture, we need to
1671	 * construct a function descriptor which the caller can use to
1672	 * call the function with the right 'gp' value. For other
1673	 * architectures and for non-functions, the value is simply
1674	 * the relocated value of the symbol.
1675	 */
1676	if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1677	    return make_function_pointer(def, defobj);
1678	else
1679	    return defobj->relocbase + def->st_value;
1680    }
1681
1682    _rtld_error("Undefined symbol \"%s\"", name);
1683    rlock_release();
1684    return NULL;
1685}
1686
1687int
1688dladdr(const void *addr, Dl_info *info)
1689{
1690    const Obj_Entry *obj;
1691    const Elf_Sym *def;
1692    void *symbol_addr;
1693    unsigned long symoffset;
1694
1695    rlock_acquire();
1696    obj = obj_from_addr(addr);
1697    if (obj == NULL) {
1698        _rtld_error("No shared object contains address");
1699	rlock_release();
1700        return 0;
1701    }
1702    info->dli_fname = obj->path;
1703    info->dli_fbase = obj->mapbase;
1704    info->dli_saddr = (void *)0;
1705    info->dli_sname = NULL;
1706
1707    /*
1708     * Walk the symbol list looking for the symbol whose address is
1709     * closest to the address sent in.
1710     */
1711    for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1712        def = obj->symtab + symoffset;
1713
1714        /*
1715         * For skip the symbol if st_shndx is either SHN_UNDEF or
1716         * SHN_COMMON.
1717         */
1718        if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1719            continue;
1720
1721        /*
1722         * If the symbol is greater than the specified address, or if it
1723         * is further away from addr than the current nearest symbol,
1724         * then reject it.
1725         */
1726        symbol_addr = obj->relocbase + def->st_value;
1727        if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1728            continue;
1729
1730        /* Update our idea of the nearest symbol. */
1731        info->dli_sname = obj->strtab + def->st_name;
1732        info->dli_saddr = symbol_addr;
1733
1734        /* Exact match? */
1735        if (info->dli_saddr == addr)
1736            break;
1737    }
1738    rlock_release();
1739    return 1;
1740}
1741
1742static void
1743linkmap_add(Obj_Entry *obj)
1744{
1745    struct link_map *l = &obj->linkmap;
1746    struct link_map *prev;
1747
1748    obj->linkmap.l_name = obj->path;
1749    obj->linkmap.l_addr = obj->mapbase;
1750    obj->linkmap.l_ld = obj->dynamic;
1751#ifdef __mips__
1752    /* GDB needs load offset on MIPS to use the symbols */
1753    obj->linkmap.l_offs = obj->relocbase;
1754#endif
1755
1756    if (r_debug.r_map == NULL) {
1757	r_debug.r_map = l;
1758	return;
1759    }
1760
1761    /*
1762     * Scan to the end of the list, but not past the entry for the
1763     * dynamic linker, which we want to keep at the very end.
1764     */
1765    for (prev = r_debug.r_map;
1766      prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1767      prev = prev->l_next)
1768	;
1769
1770    /* Link in the new entry. */
1771    l->l_prev = prev;
1772    l->l_next = prev->l_next;
1773    if (l->l_next != NULL)
1774	l->l_next->l_prev = l;
1775    prev->l_next = l;
1776}
1777
1778static void
1779linkmap_delete(Obj_Entry *obj)
1780{
1781    struct link_map *l = &obj->linkmap;
1782
1783    if (l->l_prev == NULL) {
1784	if ((r_debug.r_map = l->l_next) != NULL)
1785	    l->l_next->l_prev = NULL;
1786	return;
1787    }
1788
1789    if ((l->l_prev->l_next = l->l_next) != NULL)
1790	l->l_next->l_prev = l->l_prev;
1791}
1792
1793/*
1794 * Function for the debugger to set a breakpoint on to gain control.
1795 *
1796 * The two parameters allow the debugger to easily find and determine
1797 * what the runtime loader is doing and to whom it is doing it.
1798 *
1799 * When the loadhook trap is hit (r_debug_state, set at program
1800 * initialization), the arguments can be found on the stack:
1801 *
1802 *  +8   struct link_map *m
1803 *  +4   struct r_debug  *rd
1804 *  +0   RetAddr
1805 */
1806void
1807r_debug_state(struct r_debug* rd, struct link_map *m)
1808{
1809}
1810
1811/*
1812 * Set a pointer variable in the main program to the given value.  This
1813 * is used to set key variables such as "environ" before any of the
1814 * init functions are called.
1815 */
1816static void
1817set_program_var(const char *name, const void *value)
1818{
1819    const Obj_Entry *obj;
1820    unsigned long hash;
1821
1822    hash = elf_hash(name);
1823    for (obj = obj_main;  obj != NULL;  obj = obj->next) {
1824	const Elf_Sym *def;
1825
1826	if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
1827	    const void **addr;
1828
1829	    addr = (const void **)(obj->relocbase + def->st_value);
1830	    dbg("\"%s\": *%p <-- %p", name, addr, value);
1831	    *addr = value;
1832	    break;
1833	}
1834    }
1835}
1836
1837/*
1838 * Given a symbol name in a referencing object, find the corresponding
1839 * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1840 * no definition was found.  Returns a pointer to the Obj_Entry of the
1841 * defining object via the reference parameter DEFOBJ_OUT.
1842 */
1843static const Elf_Sym *
1844symlook_default(const char *name, unsigned long hash,
1845    const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
1846{
1847    DoneList donelist;
1848    const Elf_Sym *def;
1849    const Elf_Sym *symp;
1850    const Obj_Entry *obj;
1851    const Obj_Entry *defobj;
1852    const Objlist_Entry *elm;
1853    def = NULL;
1854    defobj = NULL;
1855    donelist_init(&donelist);
1856
1857    /* Look first in the referencing object if linked symbolically. */
1858    if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
1859	symp = symlook_obj(name, hash, refobj, in_plt);
1860	if (symp != NULL) {
1861	    def = symp;
1862	    defobj = refobj;
1863	}
1864    }
1865
1866    /* Search all objects loaded at program start up. */
1867    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1868	symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
1869	if (symp != NULL &&
1870	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1871	    def = symp;
1872	    defobj = obj;
1873	}
1874    }
1875
1876    /* Search all dlopened DAGs containing the referencing object. */
1877    STAILQ_FOREACH(elm, &refobj->dldags, link) {
1878	if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
1879	    break;
1880	symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
1881	  &donelist);
1882	if (symp != NULL &&
1883	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1884	    def = symp;
1885	    defobj = obj;
1886	}
1887    }
1888
1889    /* Search all RTLD_GLOBAL objects. */
1890    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1891	symp = symlook_list(name, hash, &list_global, &obj, in_plt, &donelist);
1892	if (symp != NULL &&
1893	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
1894	    def = symp;
1895	    defobj = obj;
1896	}
1897    }
1898
1899    /*
1900     * Search the dynamic linker itself, and possibly resolve the
1901     * symbol from there.  This is how the application links to
1902     * dynamic linker services such as dlopen.  Only the values listed
1903     * in the "exports" array can be resolved from the dynamic linker.
1904     */
1905    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1906	symp = symlook_obj(name, hash, &obj_rtld, in_plt);
1907	if (symp != NULL && is_exported(symp)) {
1908	    def = symp;
1909	    defobj = &obj_rtld;
1910	}
1911    }
1912
1913    if (def != NULL)
1914	*defobj_out = defobj;
1915    return def;
1916}
1917
1918static const Elf_Sym *
1919symlook_list(const char *name, unsigned long hash, Objlist *objlist,
1920  const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
1921{
1922    const Elf_Sym *symp;
1923    const Elf_Sym *def;
1924    const Obj_Entry *defobj;
1925    const Objlist_Entry *elm;
1926
1927    def = NULL;
1928    defobj = NULL;
1929    STAILQ_FOREACH(elm, objlist, link) {
1930	if (donelist_check(dlp, elm->obj))
1931	    continue;
1932	if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
1933	    if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1934		def = symp;
1935		defobj = elm->obj;
1936		if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1937		    break;
1938	    }
1939	}
1940    }
1941    if (def != NULL)
1942	*defobj_out = defobj;
1943    return def;
1944}
1945
1946/*
1947 * Search the symbol table of a single shared object for a symbol of
1948 * the given name.  Returns a pointer to the symbol, or NULL if no
1949 * definition was found.
1950 *
1951 * The symbol's hash value is passed in for efficiency reasons; that
1952 * eliminates many recomputations of the hash value.
1953 */
1954const Elf_Sym *
1955symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
1956  bool in_plt)
1957{
1958    if (obj->buckets != NULL) {
1959	unsigned long symnum = obj->buckets[hash % obj->nbuckets];
1960
1961	while (symnum != STN_UNDEF) {
1962	    const Elf_Sym *symp;
1963	    const char *strp;
1964
1965	    if (symnum >= obj->nchains)
1966		return NULL;	/* Bad object */
1967	    symp = obj->symtab + symnum;
1968	    strp = obj->strtab + symp->st_name;
1969
1970	    if (name[0] == strp[0] && strcmp(name, strp) == 0)
1971		return symp->st_shndx != SHN_UNDEF ||
1972		  (!in_plt && symp->st_value != 0 &&
1973		  ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
1974
1975	    symnum = obj->chains[symnum];
1976	}
1977    }
1978    return NULL;
1979}
1980
1981static void
1982trace_loaded_objects(Obj_Entry *obj)
1983{
1984    char	*fmt1, *fmt2, *fmt, *main_local;
1985    int		c;
1986
1987    if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
1988	main_local = "";
1989
1990    if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
1991	fmt1 = "\t%o => %p (%x)\n";
1992
1993    if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
1994	fmt2 = "\t%o (%x)\n";
1995
1996    for (; obj; obj = obj->next) {
1997	Needed_Entry		*needed;
1998	char			*name, *path;
1999	bool			is_lib;
2000
2001	for (needed = obj->needed; needed; needed = needed->next) {
2002	    if (needed->obj != NULL) {
2003		if (needed->obj->traced)
2004		    continue;
2005		needed->obj->traced = true;
2006		path = needed->obj->path;
2007	    } else
2008		path = "not found";
2009
2010	    name = (char *)obj->strtab + needed->name;
2011	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
2012
2013	    fmt = is_lib ? fmt1 : fmt2;
2014	    while ((c = *fmt++) != '\0') {
2015		switch (c) {
2016		default:
2017		    putchar(c);
2018		    continue;
2019		case '\\':
2020		    switch (c = *fmt) {
2021		    case '\0':
2022			continue;
2023		    case 'n':
2024			putchar('\n');
2025			break;
2026		    case 't':
2027			putchar('\t');
2028			break;
2029		    }
2030		    break;
2031		case '%':
2032		    switch (c = *fmt) {
2033		    case '\0':
2034			continue;
2035		    case '%':
2036		    default:
2037			putchar(c);
2038			break;
2039		    case 'A':
2040			printf("%s", main_local);
2041			break;
2042		    case 'a':
2043			printf("%s", obj_main->path);
2044			break;
2045		    case 'o':
2046			printf("%s", name);
2047			break;
2048#if 0
2049		    case 'm':
2050			printf("%d", sodp->sod_major);
2051			break;
2052		    case 'n':
2053			printf("%d", sodp->sod_minor);
2054			break;
2055#endif
2056		    case 'p':
2057			printf("%s", path);
2058			break;
2059		    case 'x':
2060			printf("%p", needed->obj ? needed->obj->mapbase : 0);
2061			break;
2062		    }
2063		    break;
2064		}
2065		++fmt;
2066	    }
2067	}
2068    }
2069}
2070
2071/*
2072 * Unload a dlopened object and its dependencies from memory and from
2073 * our data structures.  It is assumed that the DAG rooted in the
2074 * object has already been unreferenced, and that the object has a
2075 * reference count of 0.
2076 */
2077static void
2078unload_object(Obj_Entry *root)
2079{
2080    Obj_Entry *obj;
2081    Obj_Entry **linkp;
2082    Objlist_Entry *elm;
2083
2084    assert(root->refcount == 0);
2085
2086    /* Remove the DAG from all objects' DAG lists. */
2087    STAILQ_FOREACH(elm, &root->dagmembers , link)
2088	objlist_remove(&elm->obj->dldags, root);
2089
2090    /* Remove the DAG from the RTLD_GLOBAL list. */
2091    objlist_remove(&list_global, root);
2092
2093    /* Unmap all objects that are no longer referenced. */
2094    linkp = &obj_list->next;
2095    while ((obj = *linkp) != NULL) {
2096	if (obj->refcount == 0) {
2097	    dbg("unloading \"%s\"", obj->path);
2098	    munmap(obj->mapbase, obj->mapsize);
2099	    linkmap_delete(obj);
2100	    *linkp = obj->next;
2101	    obj_count--;
2102	    obj_free(obj);
2103	} else
2104	    linkp = &obj->next;
2105    }
2106    obj_tail = linkp;
2107}
2108
2109static void
2110unref_dag(Obj_Entry *root)
2111{
2112    const Needed_Entry *needed;
2113
2114    if (root->refcount == 0)
2115	return;
2116    root->refcount--;
2117    if (root->refcount == 0)
2118	for (needed = root->needed;  needed != NULL;  needed = needed->next)
2119	    if (needed->obj != NULL)
2120		unref_dag(needed->obj);
2121}
2122
2123/*
2124 * Non-mallocing printf, for use by malloc itself.
2125 * XXX - This doesn't belong in this module.
2126 */
2127void
2128xprintf(const char *fmt, ...)
2129{
2130    char buf[256];
2131    va_list ap;
2132
2133    va_start(ap, fmt);
2134    vsprintf(buf, fmt, ap);
2135    (void)write(STDOUT_FILENO, buf, strlen(buf));
2136    va_end(ap);
2137}
2138