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