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