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