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