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