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