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