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