]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/rtld-elf/rtld.c
Introduce implementation-private rtld interface _rtld_addr_phdr, which
[FreeBSD/FreeBSD.git] / libexec / rtld-elf / rtld.c
1 /*-
2  * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3  * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28
29 /*
30  * Dynamic linker for ELF.
31  *
32  * John Polstra <jdp@polstra.com>.
33  */
34
35 #ifndef __GNUC__
36 #error "GCC is needed to compile this file"
37 #endif
38
39 #include <sys/param.h>
40 #include <sys/mount.h>
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/sysctl.h>
44 #include <sys/uio.h>
45 #include <sys/utsname.h>
46 #include <sys/ktrace.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 #include "libmap.h"
61 #include "rtld_tls.h"
62
63 #ifndef COMPAT_32BIT
64 #define PATH_RTLD       "/libexec/ld-elf.so.1"
65 #else
66 #define PATH_RTLD       "/libexec/ld-elf32.so.1"
67 #endif
68
69 /* Types. */
70 typedef void (*func_ptr_type)();
71 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
72
73 /*
74  * This structure provides a reentrant way to keep a list of objects and
75  * check which ones have already been processed in some way.
76  */
77 typedef struct Struct_DoneList {
78     const Obj_Entry **objs;             /* Array of object pointers */
79     unsigned int num_alloc;             /* Allocated size of the array */
80     unsigned int num_used;              /* Number of array slots used */
81 } DoneList;
82
83 /*
84  * Function declarations.
85  */
86 static const char *basename(const char *);
87 static void die(void) __dead2;
88 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
89     const Elf_Dyn **);
90 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
91 static void digest_dynamic(Obj_Entry *, int);
92 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
93 static Obj_Entry *dlcheck(void *);
94 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
95 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
96 static bool donelist_check(DoneList *, const Obj_Entry *);
97 static void errmsg_restore(char *);
98 static char *errmsg_save(void);
99 static void *fill_search_info(const char *, size_t, void *);
100 static char *find_library(const char *, const Obj_Entry *);
101 static const char *gethints(void);
102 static void init_dag(Obj_Entry *);
103 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
104 static void init_rtld(caddr_t, Elf_Auxinfo **);
105 static void initlist_add_neededs(Needed_Entry *, Objlist *);
106 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
107 static bool is_exported(const Elf_Sym *);
108 static void linkmap_add(Obj_Entry *);
109 static void linkmap_delete(Obj_Entry *);
110 static int load_needed_objects(Obj_Entry *, int);
111 static int load_preload_objects(void);
112 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
113 static Obj_Entry *obj_from_addr(const void *);
114 static void objlist_call_fini(Objlist *, bool, int *);
115 static void objlist_call_init(Objlist *, int *);
116 static void objlist_clear(Objlist *);
117 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
118 static void objlist_init(Objlist *);
119 static void objlist_push_head(Objlist *, Obj_Entry *);
120 static void objlist_push_tail(Objlist *, Obj_Entry *);
121 static void objlist_remove(Objlist *, Obj_Entry *);
122 static void *path_enumerate(const char *, path_enum_proc, void *);
123 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
124 static int rtld_dirname(const char *, char *);
125 static int rtld_dirname_abs(const char *, char *);
126 static void rtld_exit(void);
127 static char *search_library_path(const char *, const char *);
128 static const void **get_program_var_addr(const char *);
129 static void set_program_var(const char *, const void *);
130 static const Elf_Sym *symlook_default(const char *, unsigned long,
131   const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
132 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
133   const Obj_Entry **, const Ver_Entry *, int, DoneList *);
134 static const Elf_Sym *symlook_needed(const char *, unsigned long,
135   const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
136   int, DoneList *);
137 static void trace_loaded_objects(Obj_Entry *);
138 static void unlink_object(Obj_Entry *);
139 static void unload_object(Obj_Entry *);
140 static void unref_dag(Obj_Entry *);
141 static void ref_dag(Obj_Entry *);
142 static int origin_subst_one(char **, const char *, const char *,
143   const char *, char *);
144 static char *origin_subst(const char *, const char *);
145 static int  rtld_verify_versions(const Objlist *);
146 static int  rtld_verify_object_versions(Obj_Entry *);
147 static void object_add_name(Obj_Entry *, const char *);
148 static int  object_match_name(const Obj_Entry *, const char *);
149 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
150 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
151     struct dl_phdr_info *phdr_info);
152
153 void r_debug_state(struct r_debug *, struct link_map *);
154
155 /*
156  * Data declarations.
157  */
158 static char *error_message;     /* Message for dlerror(), or NULL */
159 struct r_debug r_debug;         /* for GDB; */
160 static bool libmap_disable;     /* Disable libmap */
161 static char *libmap_override;   /* Maps to use in addition to libmap.conf */
162 static bool trust;              /* False for setuid and setgid programs */
163 static bool dangerous_ld_env;   /* True if environment variables have been
164                                    used to affect the libraries loaded */
165 static char *ld_bind_now;       /* Environment variable for immediate binding */
166 static char *ld_debug;          /* Environment variable for debugging */
167 static char *ld_library_path;   /* Environment variable for search path */
168 static char *ld_preload;        /* Environment variable for libraries to
169                                    load first */
170 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */
171 static char *ld_tracing;        /* Called from ldd to print libs */
172 static char *ld_utrace;         /* Use utrace() to log events. */
173 static Obj_Entry *obj_list;     /* Head of linked list of shared objects */
174 static Obj_Entry **obj_tail;    /* Link field of last object in list */
175 static Obj_Entry *obj_main;     /* The main program shared object */
176 static Obj_Entry obj_rtld;      /* The dynamic linker shared object */
177 static unsigned int obj_count;  /* Number of objects in obj_list */
178 static unsigned int obj_loads;  /* Number of objects in obj_list */
179
180 static Objlist list_global =    /* Objects dlopened with RTLD_GLOBAL */
181   STAILQ_HEAD_INITIALIZER(list_global);
182 static Objlist list_main =      /* Objects loaded at program startup */
183   STAILQ_HEAD_INITIALIZER(list_main);
184 static Objlist list_fini =      /* Objects needing fini() calls */
185   STAILQ_HEAD_INITIALIZER(list_fini);
186
187 static Elf_Sym sym_zero;        /* For resolving undefined weak refs. */
188
189 #define GDB_STATE(s,m)  r_debug.r_state = s; r_debug_state(&r_debug,m);
190
191 extern Elf_Dyn _DYNAMIC;
192 #pragma weak _DYNAMIC
193 #ifndef RTLD_IS_DYNAMIC
194 #define RTLD_IS_DYNAMIC()       (&_DYNAMIC != NULL)
195 #endif
196
197 int osreldate, pagesize;
198
199 /*
200  * These are the functions the dynamic linker exports to application
201  * programs.  They are the only symbols the dynamic linker is willing
202  * to export from itself.
203  */
204 static func_ptr_type exports[] = {
205     (func_ptr_type) &_rtld_error,
206     (func_ptr_type) &dlclose,
207     (func_ptr_type) &dlerror,
208     (func_ptr_type) &dlopen,
209     (func_ptr_type) &dlsym,
210     (func_ptr_type) &dlfunc,
211     (func_ptr_type) &dlvsym,
212     (func_ptr_type) &dladdr,
213     (func_ptr_type) &dllockinit,
214     (func_ptr_type) &dlinfo,
215     (func_ptr_type) &_rtld_thread_init,
216 #ifdef __i386__
217     (func_ptr_type) &___tls_get_addr,
218 #endif
219     (func_ptr_type) &__tls_get_addr,
220     (func_ptr_type) &_rtld_allocate_tls,
221     (func_ptr_type) &_rtld_free_tls,
222     (func_ptr_type) &dl_iterate_phdr,
223     (func_ptr_type) &_rtld_atfork_pre,
224     (func_ptr_type) &_rtld_atfork_post,
225     (func_ptr_type) &_rtld_addr_phdr,
226     NULL
227 };
228
229 /*
230  * Global declarations normally provided by crt1.  The dynamic linker is
231  * not built with crt1, so we have to provide them ourselves.
232  */
233 char *__progname;
234 char **environ;
235
236 /*
237  * Globals to control TLS allocation.
238  */
239 size_t tls_last_offset;         /* Static TLS offset of last module */
240 size_t tls_last_size;           /* Static TLS size of last module */
241 size_t tls_static_space;        /* Static TLS space allocated */
242 int tls_dtv_generation = 1;     /* Used to detect when dtv size changes  */
243 int tls_max_index = 1;          /* Largest module index allocated */
244
245 /*
246  * Fill in a DoneList with an allocation large enough to hold all of
247  * the currently-loaded objects.  Keep this as a macro since it calls
248  * alloca and we want that to occur within the scope of the caller.
249  */
250 #define donelist_init(dlp)                                      \
251     ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),   \
252     assert((dlp)->objs != NULL),                                \
253     (dlp)->num_alloc = obj_count,                               \
254     (dlp)->num_used = 0)
255
256 #define UTRACE_DLOPEN_START             1
257 #define UTRACE_DLOPEN_STOP              2
258 #define UTRACE_DLCLOSE_START            3
259 #define UTRACE_DLCLOSE_STOP             4
260 #define UTRACE_LOAD_OBJECT              5
261 #define UTRACE_UNLOAD_OBJECT            6
262 #define UTRACE_ADD_RUNDEP               7
263 #define UTRACE_PRELOAD_FINISHED         8
264 #define UTRACE_INIT_CALL                9
265 #define UTRACE_FINI_CALL                10
266
267 struct utrace_rtld {
268         char sig[4];                    /* 'RTLD' */
269         int event;
270         void *handle;
271         void *mapbase;                  /* Used for 'parent' and 'init/fini' */
272         size_t mapsize;
273         int refcnt;                     /* Used for 'mode' */
274         char name[MAXPATHLEN];
275 };
276
277 #define LD_UTRACE(e, h, mb, ms, r, n) do {                      \
278         if (ld_utrace != NULL)                                  \
279                 ld_utrace_log(e, h, mb, ms, r, n);              \
280 } while (0)
281
282 static void
283 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
284     int refcnt, const char *name)
285 {
286         struct utrace_rtld ut;
287
288         ut.sig[0] = 'R';
289         ut.sig[1] = 'T';
290         ut.sig[2] = 'L';
291         ut.sig[3] = 'D';
292         ut.event = event;
293         ut.handle = handle;
294         ut.mapbase = mapbase;
295         ut.mapsize = mapsize;
296         ut.refcnt = refcnt;
297         bzero(ut.name, sizeof(ut.name));
298         if (name)
299                 strlcpy(ut.name, name, sizeof(ut.name));
300         utrace(&ut, sizeof(ut));
301 }
302
303 /*
304  * Main entry point for dynamic linking.  The first argument is the
305  * stack pointer.  The stack is expected to be laid out as described
306  * in the SVR4 ABI specification, Intel 386 Processor Supplement.
307  * Specifically, the stack pointer points to a word containing
308  * ARGC.  Following that in the stack is a null-terminated sequence
309  * of pointers to argument strings.  Then comes a null-terminated
310  * sequence of pointers to environment strings.  Finally, there is a
311  * sequence of "auxiliary vector" entries.
312  *
313  * The second argument points to a place to store the dynamic linker's
314  * exit procedure pointer and the third to a place to store the main
315  * program's object.
316  *
317  * The return value is the main program's entry point.
318  */
319 func_ptr_type
320 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
321 {
322     Elf_Auxinfo *aux_info[AT_COUNT];
323     int i;
324     int argc;
325     char **argv;
326     char **env;
327     Elf_Auxinfo *aux;
328     Elf_Auxinfo *auxp;
329     const char *argv0;
330     Objlist_Entry *entry;
331     Obj_Entry *obj;
332     Obj_Entry **preload_tail;
333     Objlist initlist;
334     int lockstate;
335
336     /*
337      * On entry, the dynamic linker itself has not been relocated yet.
338      * Be very careful not to reference any global data until after
339      * init_rtld has returned.  It is OK to reference file-scope statics
340      * and string constants, and to call static and global functions.
341      */
342
343     /* Find the auxiliary vector on the stack. */
344     argc = *sp++;
345     argv = (char **) sp;
346     sp += argc + 1;     /* Skip over arguments and NULL terminator */
347     env = (char **) sp;
348     while (*sp++ != 0)  /* Skip over environment, and NULL terminator */
349         ;
350     aux = (Elf_Auxinfo *) sp;
351
352     /* Digest the auxiliary vector. */
353     for (i = 0;  i < AT_COUNT;  i++)
354         aux_info[i] = NULL;
355     for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
356         if (auxp->a_type < AT_COUNT)
357             aux_info[auxp->a_type] = auxp;
358     }
359
360     /* Initialize and relocate ourselves. */
361     assert(aux_info[AT_BASE] != NULL);
362     init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
363
364     __progname = obj_rtld.path;
365     argv0 = argv[0] != NULL ? argv[0] : "(null)";
366     environ = env;
367
368     trust = !issetugid();
369
370     ld_bind_now = getenv(LD_ "BIND_NOW");
371     /* 
372      * If the process is tainted, then we un-set the dangerous environment
373      * variables.  The process will be marked as tainted until setuid(2)
374      * is called.  If any child process calls setuid(2) we do not want any
375      * future processes to honor the potentially un-safe variables.
376      */
377     if (!trust) {
378         if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
379             unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
380             unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH")) {
381                 _rtld_error("environment corrupt; aborting");
382                 die();
383         }
384     }
385     ld_debug = getenv(LD_ "DEBUG");
386     libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
387     libmap_override = getenv(LD_ "LIBMAP");
388     ld_library_path = getenv(LD_ "LIBRARY_PATH");
389     ld_preload = getenv(LD_ "PRELOAD");
390     ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
391     dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
392         (ld_library_path != NULL) || (ld_preload != NULL) ||
393         (ld_elf_hints_path != NULL);
394     ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
395     ld_utrace = getenv(LD_ "UTRACE");
396
397     if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
398         ld_elf_hints_path = _PATH_ELF_HINTS;
399
400     if (ld_debug != NULL && *ld_debug != '\0')
401         debug = 1;
402     dbg("%s is initialized, base address = %p", __progname,
403         (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
404     dbg("RTLD dynamic = %p", obj_rtld.dynamic);
405     dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
406
407     /*
408      * Load the main program, or process its program header if it is
409      * already loaded.
410      */
411     if (aux_info[AT_EXECFD] != NULL) {  /* Load the main program. */
412         int fd = aux_info[AT_EXECFD]->a_un.a_val;
413         dbg("loading main program");
414         obj_main = map_object(fd, argv0, NULL);
415         close(fd);
416         if (obj_main == NULL)
417             die();
418     } else {                            /* Main program already loaded. */
419         const Elf_Phdr *phdr;
420         int phnum;
421         caddr_t entry;
422
423         dbg("processing main program's program header");
424         assert(aux_info[AT_PHDR] != NULL);
425         phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
426         assert(aux_info[AT_PHNUM] != NULL);
427         phnum = aux_info[AT_PHNUM]->a_un.a_val;
428         assert(aux_info[AT_PHENT] != NULL);
429         assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
430         assert(aux_info[AT_ENTRY] != NULL);
431         entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
432         if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
433             die();
434     }
435
436     if (aux_info[AT_EXECPATH] != 0) {
437             char *kexecpath;
438             char buf[MAXPATHLEN];
439
440             kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
441             dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
442             if (kexecpath[0] == '/')
443                     obj_main->path = kexecpath;
444             else if (getcwd(buf, sizeof(buf)) == NULL ||
445                      strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
446                      strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
447                     obj_main->path = xstrdup(argv0);
448             else
449                     obj_main->path = xstrdup(buf);
450     } else {
451             dbg("No AT_EXECPATH");
452             obj_main->path = xstrdup(argv0);
453     }
454     dbg("obj_main path %s", obj_main->path);
455     obj_main->mainprog = true;
456
457     /*
458      * Get the actual dynamic linker pathname from the executable if
459      * possible.  (It should always be possible.)  That ensures that
460      * gdb will find the right dynamic linker even if a non-standard
461      * one is being used.
462      */
463     if (obj_main->interp != NULL &&
464       strcmp(obj_main->interp, obj_rtld.path) != 0) {
465         free(obj_rtld.path);
466         obj_rtld.path = xstrdup(obj_main->interp);
467         __progname = obj_rtld.path;
468     }
469
470     digest_dynamic(obj_main, 0);
471
472     linkmap_add(obj_main);
473     linkmap_add(&obj_rtld);
474
475     /* Link the main program into the list of objects. */
476     *obj_tail = obj_main;
477     obj_tail = &obj_main->next;
478     obj_count++;
479     obj_loads++;
480     /* Make sure we don't call the main program's init and fini functions. */
481     obj_main->init = obj_main->fini = (Elf_Addr)NULL;
482
483     /* Initialize a fake symbol for resolving undefined weak references. */
484     sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
485     sym_zero.st_shndx = SHN_UNDEF;
486     sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
487
488     if (!libmap_disable)
489         libmap_disable = (bool)lm_init(libmap_override);
490
491     dbg("loading LD_PRELOAD libraries");
492     if (load_preload_objects() == -1)
493         die();
494     preload_tail = obj_tail;
495
496     dbg("loading needed objects");
497     if (load_needed_objects(obj_main, 0) == -1)
498         die();
499
500     /* Make a list of all objects loaded at startup. */
501     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
502         objlist_push_tail(&list_main, obj);
503         obj->refcount++;
504     }
505
506     dbg("checking for required versions");
507     if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
508         die();
509
510     if (ld_tracing) {           /* We're done */
511         trace_loaded_objects(obj_main);
512         exit(0);
513     }
514
515     if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
516        dump_relocations(obj_main);
517        exit (0);
518     }
519
520     /* setup TLS for main thread */
521     dbg("initializing initial thread local storage");
522     STAILQ_FOREACH(entry, &list_main, link) {
523         /*
524          * Allocate all the initial objects out of the static TLS
525          * block even if they didn't ask for it.
526          */
527         allocate_tls_offset(entry->obj);
528     }
529     allocate_initial_tls(obj_list);
530
531     if (relocate_objects(obj_main,
532         ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
533         die();
534
535     dbg("doing copy relocations");
536     if (do_copy_relocations(obj_main) == -1)
537         die();
538
539     if (getenv(LD_ "DUMP_REL_POST") != NULL) {
540        dump_relocations(obj_main);
541        exit (0);
542     }
543
544     dbg("initializing key program variables");
545     set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
546     set_program_var("environ", env);
547     set_program_var("__elf_aux_vector", aux);
548
549     dbg("initializing thread locks");
550     lockdflt_init();
551
552     /* Make a list of init functions to call. */
553     objlist_init(&initlist);
554     initlist_add_objects(obj_list, preload_tail, &initlist);
555
556     r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
557
558     lockstate = wlock_acquire(rtld_bind_lock);
559     objlist_call_init(&initlist, &lockstate);
560     objlist_clear(&initlist);
561     wlock_release(rtld_bind_lock, lockstate);
562
563     dbg("transferring control to program entry point = %p", obj_main->entry);
564
565     /* Return the exit procedure and the program entry point. */
566     *exit_proc = rtld_exit;
567     *objp = obj_main;
568     return (func_ptr_type) obj_main->entry;
569 }
570
571 Elf_Addr
572 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
573 {
574     const Elf_Rel *rel;
575     const Elf_Sym *def;
576     const Obj_Entry *defobj;
577     Elf_Addr *where;
578     Elf_Addr target;
579     int lockstate;
580
581     lockstate = rlock_acquire(rtld_bind_lock);
582     if (obj->pltrel)
583         rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
584     else
585         rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
586
587     where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
588     def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
589     if (def == NULL)
590         die();
591
592     target = (Elf_Addr)(defobj->relocbase + def->st_value);
593
594     dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
595       defobj->strtab + def->st_name, basename(obj->path),
596       (void *)target, basename(defobj->path));
597
598     /*
599      * Write the new contents for the jmpslot. Note that depending on
600      * architecture, the value which we need to return back to the
601      * lazy binding trampoline may or may not be the target
602      * address. The value returned from reloc_jmpslot() is the value
603      * that the trampoline needs.
604      */
605     target = reloc_jmpslot(where, target, defobj, obj, rel);
606     rlock_release(rtld_bind_lock, lockstate);
607     return target;
608 }
609
610 /*
611  * Error reporting function.  Use it like printf.  If formats the message
612  * into a buffer, and sets things up so that the next call to dlerror()
613  * will return the message.
614  */
615 void
616 _rtld_error(const char *fmt, ...)
617 {
618     static char buf[512];
619     va_list ap;
620
621     va_start(ap, fmt);
622     vsnprintf(buf, sizeof buf, fmt, ap);
623     error_message = buf;
624     va_end(ap);
625 }
626
627 /*
628  * Return a dynamically-allocated copy of the current error message, if any.
629  */
630 static char *
631 errmsg_save(void)
632 {
633     return error_message == NULL ? NULL : xstrdup(error_message);
634 }
635
636 /*
637  * Restore the current error message from a copy which was previously saved
638  * by errmsg_save().  The copy is freed.
639  */
640 static void
641 errmsg_restore(char *saved_msg)
642 {
643     if (saved_msg == NULL)
644         error_message = NULL;
645     else {
646         _rtld_error("%s", saved_msg);
647         free(saved_msg);
648     }
649 }
650
651 static const char *
652 basename(const char *name)
653 {
654     const char *p = strrchr(name, '/');
655     return p != NULL ? p + 1 : name;
656 }
657
658 static struct utsname uts;
659
660 static int
661 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
662     char *may_free)
663 {
664     const char *p, *p1;
665     char *res1;
666     int subst_len;
667     int kw_len;
668
669     res1 = *res = NULL;
670     p = real;
671     subst_len = kw_len = 0;
672     for (;;) {
673          p1 = strstr(p, kw);
674          if (p1 != NULL) {
675              if (subst_len == 0) {
676                  subst_len = strlen(subst);
677                  kw_len = strlen(kw);
678              }
679              if (*res == NULL) {
680                  *res = xmalloc(PATH_MAX);
681                  res1 = *res;
682              }
683              if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
684                  _rtld_error("Substitution of %s in %s cannot be performed",
685                      kw, real);
686                  if (may_free != NULL)
687                      free(may_free);
688                  free(res);
689                  return (false);
690              }
691              memcpy(res1, p, p1 - p);
692              res1 += p1 - p;
693              memcpy(res1, subst, subst_len);
694              res1 += subst_len;
695              p = p1 + kw_len;
696          } else {
697             if (*res == NULL) {
698                 if (may_free != NULL)
699                     *res = may_free;
700                 else
701                     *res = xstrdup(real);
702                 return (true);
703             }
704             *res1 = '\0';
705             if (may_free != NULL)
706                 free(may_free);
707             if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
708                 free(res);
709                 return (false);
710             }
711             return (true);
712          }
713     }
714 }
715
716 static char *
717 origin_subst(const char *real, const char *origin_path)
718 {
719     char *res1, *res2, *res3, *res4;
720
721     if (uts.sysname[0] == '\0') {
722         if (uname(&uts) != 0) {
723             _rtld_error("utsname failed: %d", errno);
724             return (NULL);
725         }
726     }
727     if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
728         !origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
729         !origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
730         !origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
731             return (NULL);
732     return (res4);
733 }
734
735 static void
736 die(void)
737 {
738     const char *msg = dlerror();
739
740     if (msg == NULL)
741         msg = "Fatal error";
742     errx(1, "%s", msg);
743 }
744
745 /*
746  * Process a shared object's DYNAMIC section, and save the important
747  * information in its Obj_Entry structure.
748  */
749 static void
750 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
751     const Elf_Dyn **dyn_soname)
752 {
753     const Elf_Dyn *dynp;
754     Needed_Entry **needed_tail = &obj->needed;
755     int plttype = DT_REL;
756
757     *dyn_rpath = NULL;
758     *dyn_soname = NULL;
759
760     obj->bind_now = false;
761     for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
762         switch (dynp->d_tag) {
763
764         case DT_REL:
765             obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
766             break;
767
768         case DT_RELSZ:
769             obj->relsize = dynp->d_un.d_val;
770             break;
771
772         case DT_RELENT:
773             assert(dynp->d_un.d_val == sizeof(Elf_Rel));
774             break;
775
776         case DT_JMPREL:
777             obj->pltrel = (const Elf_Rel *)
778               (obj->relocbase + dynp->d_un.d_ptr);
779             break;
780
781         case DT_PLTRELSZ:
782             obj->pltrelsize = dynp->d_un.d_val;
783             break;
784
785         case DT_RELA:
786             obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
787             break;
788
789         case DT_RELASZ:
790             obj->relasize = dynp->d_un.d_val;
791             break;
792
793         case DT_RELAENT:
794             assert(dynp->d_un.d_val == sizeof(Elf_Rela));
795             break;
796
797         case DT_PLTREL:
798             plttype = dynp->d_un.d_val;
799             assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
800             break;
801
802         case DT_SYMTAB:
803             obj->symtab = (const Elf_Sym *)
804               (obj->relocbase + dynp->d_un.d_ptr);
805             break;
806
807         case DT_SYMENT:
808             assert(dynp->d_un.d_val == sizeof(Elf_Sym));
809             break;
810
811         case DT_STRTAB:
812             obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
813             break;
814
815         case DT_STRSZ:
816             obj->strsize = dynp->d_un.d_val;
817             break;
818
819         case DT_VERNEED:
820             obj->verneed = (const Elf_Verneed *) (obj->relocbase +
821                 dynp->d_un.d_val);
822             break;
823
824         case DT_VERNEEDNUM:
825             obj->verneednum = dynp->d_un.d_val;
826             break;
827
828         case DT_VERDEF:
829             obj->verdef = (const Elf_Verdef *) (obj->relocbase +
830                 dynp->d_un.d_val);
831             break;
832
833         case DT_VERDEFNUM:
834             obj->verdefnum = dynp->d_un.d_val;
835             break;
836
837         case DT_VERSYM:
838             obj->versyms = (const Elf_Versym *)(obj->relocbase +
839                 dynp->d_un.d_val);
840             break;
841
842         case DT_HASH:
843             {
844                 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
845                   (obj->relocbase + dynp->d_un.d_ptr);
846                 obj->nbuckets = hashtab[0];
847                 obj->nchains = hashtab[1];
848                 obj->buckets = hashtab + 2;
849                 obj->chains = obj->buckets + obj->nbuckets;
850             }
851             break;
852
853         case DT_NEEDED:
854             if (!obj->rtld) {
855                 Needed_Entry *nep = NEW(Needed_Entry);
856                 nep->name = dynp->d_un.d_val;
857                 nep->obj = NULL;
858                 nep->next = NULL;
859
860                 *needed_tail = nep;
861                 needed_tail = &nep->next;
862             }
863             break;
864
865         case DT_PLTGOT:
866             obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
867             break;
868
869         case DT_TEXTREL:
870             obj->textrel = true;
871             break;
872
873         case DT_SYMBOLIC:
874             obj->symbolic = true;
875             break;
876
877         case DT_RPATH:
878         case DT_RUNPATH:        /* XXX: process separately */
879             /*
880              * We have to wait until later to process this, because we
881              * might not have gotten the address of the string table yet.
882              */
883             *dyn_rpath = dynp;
884             break;
885
886         case DT_SONAME:
887             *dyn_soname = dynp;
888             break;
889
890         case DT_INIT:
891             obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
892             break;
893
894         case DT_FINI:
895             obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
896             break;
897
898         /*
899          * Don't process DT_DEBUG on MIPS as the dynamic section
900          * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
901          */
902
903 #ifndef __mips__
904         case DT_DEBUG:
905             /* XXX - not implemented yet */
906             if (!early)
907                 dbg("Filling in DT_DEBUG entry");
908             ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
909             break;
910 #endif
911
912         case DT_FLAGS:
913                 if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
914                     obj->z_origin = true;
915                 if (dynp->d_un.d_val & DF_SYMBOLIC)
916                     obj->symbolic = true;
917                 if (dynp->d_un.d_val & DF_TEXTREL)
918                     obj->textrel = true;
919                 if (dynp->d_un.d_val & DF_BIND_NOW)
920                     obj->bind_now = true;
921                 if (dynp->d_un.d_val & DF_STATIC_TLS)
922                     ;
923             break;
924 #ifdef __mips__
925         case DT_MIPS_LOCAL_GOTNO:
926                 obj->local_gotno = dynp->d_un.d_val;
927             break;
928
929         case DT_MIPS_SYMTABNO:
930                 obj->symtabno = dynp->d_un.d_val;
931                 break;
932
933         case DT_MIPS_GOTSYM:
934                 obj->gotsym = dynp->d_un.d_val;
935                 break;
936
937         case DT_MIPS_RLD_MAP:
938 #ifdef notyet
939                 if (!early)
940                         dbg("Filling in DT_DEBUG entry");
941                 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
942 #endif
943                 break;
944 #endif
945
946         case DT_FLAGS_1:
947                 if (dynp->d_un.d_val & DF_1_NOOPEN)
948                     obj->z_noopen = true;
949                 if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
950                     obj->z_origin = true;
951                 if (dynp->d_un.d_val & DF_1_GLOBAL)
952                         /* XXX */;
953                 if (dynp->d_un.d_val & DF_1_BIND_NOW)
954                     obj->bind_now = true;
955                 if (dynp->d_un.d_val & DF_1_NODELETE)
956                     obj->z_nodelete = true;
957             break;
958
959         default:
960             if (!early) {
961                 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
962                     (long)dynp->d_tag);
963             }
964             break;
965         }
966     }
967
968     obj->traced = false;
969
970     if (plttype == DT_RELA) {
971         obj->pltrela = (const Elf_Rela *) obj->pltrel;
972         obj->pltrel = NULL;
973         obj->pltrelasize = obj->pltrelsize;
974         obj->pltrelsize = 0;
975     }
976 }
977
978 static void
979 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
980     const Elf_Dyn *dyn_soname)
981 {
982
983     if (obj->z_origin && obj->origin_path == NULL) {
984         obj->origin_path = xmalloc(PATH_MAX);
985         if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
986             die();
987     }
988
989     if (dyn_rpath != NULL) {
990         obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
991         if (obj->z_origin)
992             obj->rpath = origin_subst(obj->rpath, obj->origin_path);
993     }
994
995     if (dyn_soname != NULL)
996         object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
997 }
998
999 static void
1000 digest_dynamic(Obj_Entry *obj, int early)
1001 {
1002         const Elf_Dyn *dyn_rpath;
1003         const Elf_Dyn *dyn_soname;
1004
1005         digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1006         digest_dynamic2(obj, dyn_rpath, dyn_soname);
1007 }
1008
1009 /*
1010  * Process a shared object's program header.  This is used only for the
1011  * main program, when the kernel has already loaded the main program
1012  * into memory before calling the dynamic linker.  It creates and
1013  * returns an Obj_Entry structure.
1014  */
1015 static Obj_Entry *
1016 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1017 {
1018     Obj_Entry *obj;
1019     const Elf_Phdr *phlimit = phdr + phnum;
1020     const Elf_Phdr *ph;
1021     int nsegs = 0;
1022
1023     obj = obj_new();
1024     for (ph = phdr;  ph < phlimit;  ph++) {
1025         if (ph->p_type != PT_PHDR)
1026             continue;
1027
1028         obj->phdr = phdr;
1029         obj->phsize = ph->p_memsz;
1030         obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1031         break;
1032     }
1033
1034     for (ph = phdr;  ph < phlimit;  ph++) {
1035         switch (ph->p_type) {
1036
1037         case PT_INTERP:
1038             obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1039             break;
1040
1041         case PT_LOAD:
1042             if (nsegs == 0) {   /* First load segment */
1043                 obj->vaddrbase = trunc_page(ph->p_vaddr);
1044                 obj->mapbase = obj->vaddrbase + obj->relocbase;
1045                 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1046                   obj->vaddrbase;
1047             } else {            /* Last load segment */
1048                 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1049                   obj->vaddrbase;
1050             }
1051             nsegs++;
1052             break;
1053
1054         case PT_DYNAMIC:
1055             obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1056             break;
1057
1058         case PT_TLS:
1059             obj->tlsindex = 1;
1060             obj->tlssize = ph->p_memsz;
1061             obj->tlsalign = ph->p_align;
1062             obj->tlsinitsize = ph->p_filesz;
1063             obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1064             break;
1065         }
1066     }
1067     if (nsegs < 1) {
1068         _rtld_error("%s: too few PT_LOAD segments", path);
1069         return NULL;
1070     }
1071
1072     obj->entry = entry;
1073     return obj;
1074 }
1075
1076 static Obj_Entry *
1077 dlcheck(void *handle)
1078 {
1079     Obj_Entry *obj;
1080
1081     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1082         if (obj == (Obj_Entry *) handle)
1083             break;
1084
1085     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1086         _rtld_error("Invalid shared object handle %p", handle);
1087         return NULL;
1088     }
1089     return obj;
1090 }
1091
1092 /*
1093  * If the given object is already in the donelist, return true.  Otherwise
1094  * add the object to the list and return false.
1095  */
1096 static bool
1097 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1098 {
1099     unsigned int i;
1100
1101     for (i = 0;  i < dlp->num_used;  i++)
1102         if (dlp->objs[i] == obj)
1103             return true;
1104     /*
1105      * Our donelist allocation should always be sufficient.  But if
1106      * our threads locking isn't working properly, more shared objects
1107      * could have been loaded since we allocated the list.  That should
1108      * never happen, but we'll handle it properly just in case it does.
1109      */
1110     if (dlp->num_used < dlp->num_alloc)
1111         dlp->objs[dlp->num_used++] = obj;
1112     return false;
1113 }
1114
1115 /*
1116  * Hash function for symbol table lookup.  Don't even think about changing
1117  * this.  It is specified by the System V ABI.
1118  */
1119 unsigned long
1120 elf_hash(const char *name)
1121 {
1122     const unsigned char *p = (const unsigned char *) name;
1123     unsigned long h = 0;
1124     unsigned long g;
1125
1126     while (*p != '\0') {
1127         h = (h << 4) + *p++;
1128         if ((g = h & 0xf0000000) != 0)
1129             h ^= g >> 24;
1130         h &= ~g;
1131     }
1132     return h;
1133 }
1134
1135 /*
1136  * Find the library with the given name, and return its full pathname.
1137  * The returned string is dynamically allocated.  Generates an error
1138  * message and returns NULL if the library cannot be found.
1139  *
1140  * If the second argument is non-NULL, then it refers to an already-
1141  * loaded shared object, whose library search path will be searched.
1142  *
1143  * The search order is:
1144  *   LD_LIBRARY_PATH
1145  *   rpath in the referencing file
1146  *   ldconfig hints
1147  *   /lib:/usr/lib
1148  */
1149 static char *
1150 find_library(const char *xname, const Obj_Entry *refobj)
1151 {
1152     char *pathname;
1153     char *name;
1154
1155     if (strchr(xname, '/') != NULL) {   /* Hard coded pathname */
1156         if (xname[0] != '/' && !trust) {
1157             _rtld_error("Absolute pathname required for shared object \"%s\"",
1158               xname);
1159             return NULL;
1160         }
1161         if (refobj != NULL && refobj->z_origin)
1162             return origin_subst(xname, refobj->origin_path);
1163         else
1164             return xstrdup(xname);
1165     }
1166
1167     if (libmap_disable || (refobj == NULL) ||
1168         (name = lm_find(refobj->path, xname)) == NULL)
1169         name = (char *)xname;
1170
1171     dbg(" Searching for \"%s\"", name);
1172
1173     if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1174       (refobj != NULL &&
1175       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1176       (pathname = search_library_path(name, gethints())) != NULL ||
1177       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1178         return pathname;
1179
1180     if(refobj != NULL && refobj->path != NULL) {
1181         _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1182           name, basename(refobj->path));
1183     } else {
1184         _rtld_error("Shared object \"%s\" not found", name);
1185     }
1186     return NULL;
1187 }
1188
1189 /*
1190  * Given a symbol number in a referencing object, find the corresponding
1191  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1192  * no definition was found.  Returns a pointer to the Obj_Entry of the
1193  * defining object via the reference parameter DEFOBJ_OUT.
1194  */
1195 const Elf_Sym *
1196 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1197     const Obj_Entry **defobj_out, int flags, SymCache *cache)
1198 {
1199     const Elf_Sym *ref;
1200     const Elf_Sym *def;
1201     const Obj_Entry *defobj;
1202     const Ver_Entry *ventry;
1203     const char *name;
1204     unsigned long hash;
1205
1206     /*
1207      * If we have already found this symbol, get the information from
1208      * the cache.
1209      */
1210     if (symnum >= refobj->nchains)
1211         return NULL;    /* Bad object */
1212     if (cache != NULL && cache[symnum].sym != NULL) {
1213         *defobj_out = cache[symnum].obj;
1214         return cache[symnum].sym;
1215     }
1216
1217     ref = refobj->symtab + symnum;
1218     name = refobj->strtab + ref->st_name;
1219     defobj = NULL;
1220
1221     /*
1222      * We don't have to do a full scale lookup if the symbol is local.
1223      * We know it will bind to the instance in this load module; to
1224      * which we already have a pointer (ie ref). By not doing a lookup,
1225      * we not only improve performance, but it also avoids unresolvable
1226      * symbols when local symbols are not in the hash table. This has
1227      * been seen with the ia64 toolchain.
1228      */
1229     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1230         if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1231             _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1232                 symnum);
1233         }
1234         ventry = fetch_ventry(refobj, symnum);
1235         hash = elf_hash(name);
1236         def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1237     } else {
1238         def = ref;
1239         defobj = refobj;
1240     }
1241
1242     /*
1243      * If we found no definition and the reference is weak, treat the
1244      * symbol as having the value zero.
1245      */
1246     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1247         def = &sym_zero;
1248         defobj = obj_main;
1249     }
1250
1251     if (def != NULL) {
1252         *defobj_out = defobj;
1253         /* Record the information in the cache to avoid subsequent lookups. */
1254         if (cache != NULL) {
1255             cache[symnum].sym = def;
1256             cache[symnum].obj = defobj;
1257         }
1258     } else {
1259         if (refobj != &obj_rtld)
1260             _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1261     }
1262     return def;
1263 }
1264
1265 /*
1266  * Return the search path from the ldconfig hints file, reading it if
1267  * necessary.  Returns NULL if there are problems with the hints file,
1268  * or if the search path there is empty.
1269  */
1270 static const char *
1271 gethints(void)
1272 {
1273     static char *hints;
1274
1275     if (hints == NULL) {
1276         int fd;
1277         struct elfhints_hdr hdr;
1278         char *p;
1279
1280         /* Keep from trying again in case the hints file is bad. */
1281         hints = "";
1282
1283         if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1284             return NULL;
1285         if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1286           hdr.magic != ELFHINTS_MAGIC ||
1287           hdr.version != 1) {
1288             close(fd);
1289             return NULL;
1290         }
1291         p = xmalloc(hdr.dirlistlen + 1);
1292         if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1293           read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1294             free(p);
1295             close(fd);
1296             return NULL;
1297         }
1298         hints = p;
1299         close(fd);
1300     }
1301     return hints[0] != '\0' ? hints : NULL;
1302 }
1303
1304 static void
1305 init_dag(Obj_Entry *root)
1306 {
1307     DoneList donelist;
1308
1309     donelist_init(&donelist);
1310     init_dag1(root, root, &donelist);
1311 }
1312
1313 static void
1314 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1315 {
1316     const Needed_Entry *needed;
1317
1318     if (donelist_check(dlp, obj))
1319         return;
1320
1321     obj->refcount++;
1322     objlist_push_tail(&obj->dldags, root);
1323     objlist_push_tail(&root->dagmembers, obj);
1324     for (needed = obj->needed;  needed != NULL;  needed = needed->next)
1325         if (needed->obj != NULL)
1326             init_dag1(root, needed->obj, dlp);
1327 }
1328
1329 /*
1330  * Initialize the dynamic linker.  The argument is the address at which
1331  * the dynamic linker has been mapped into memory.  The primary task of
1332  * this function is to relocate the dynamic linker.
1333  */
1334 static void
1335 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1336 {
1337     Obj_Entry objtmp;   /* Temporary rtld object */
1338     const Elf_Dyn *dyn_rpath;
1339     const Elf_Dyn *dyn_soname;
1340
1341     /*
1342      * Conjure up an Obj_Entry structure for the dynamic linker.
1343      *
1344      * The "path" member can't be initialized yet because string constants
1345      * cannot yet be accessed. Below we will set it correctly.
1346      */
1347     memset(&objtmp, 0, sizeof(objtmp));
1348     objtmp.path = NULL;
1349     objtmp.rtld = true;
1350     objtmp.mapbase = mapbase;
1351 #ifdef PIC
1352     objtmp.relocbase = mapbase;
1353 #endif
1354     if (RTLD_IS_DYNAMIC()) {
1355         objtmp.dynamic = rtld_dynamic(&objtmp);
1356         digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1357         assert(objtmp.needed == NULL);
1358 #if !defined(__mips__)
1359         /* MIPS and SH{3,5} have a bogus DT_TEXTREL. */
1360         assert(!objtmp.textrel);
1361 #endif
1362
1363         /*
1364          * Temporarily put the dynamic linker entry into the object list, so
1365          * that symbols can be found.
1366          */
1367
1368         relocate_objects(&objtmp, true, &objtmp);
1369     }
1370
1371     /* Initialize the object list. */
1372     obj_tail = &obj_list;
1373
1374     /* Now that non-local variables can be accesses, copy out obj_rtld. */
1375     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1376
1377     if (aux_info[AT_PAGESZ] != NULL)
1378             pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1379     if (aux_info[AT_OSRELDATE] != NULL)
1380             osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1381
1382     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1383
1384     /* Replace the path with a dynamically allocated copy. */
1385     obj_rtld.path = xstrdup(PATH_RTLD);
1386
1387     r_debug.r_brk = r_debug_state;
1388     r_debug.r_state = RT_CONSISTENT;
1389 }
1390
1391 /*
1392  * Add the init functions from a needed object list (and its recursive
1393  * needed objects) to "list".  This is not used directly; it is a helper
1394  * function for initlist_add_objects().  The write lock must be held
1395  * when this function is called.
1396  */
1397 static void
1398 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1399 {
1400     /* Recursively process the successor needed objects. */
1401     if (needed->next != NULL)
1402         initlist_add_neededs(needed->next, list);
1403
1404     /* Process the current needed object. */
1405     if (needed->obj != NULL)
1406         initlist_add_objects(needed->obj, &needed->obj->next, list);
1407 }
1408
1409 /*
1410  * Scan all of the DAGs rooted in the range of objects from "obj" to
1411  * "tail" and add their init functions to "list".  This recurses over
1412  * the DAGs and ensure the proper init ordering such that each object's
1413  * needed libraries are initialized before the object itself.  At the
1414  * same time, this function adds the objects to the global finalization
1415  * list "list_fini" in the opposite order.  The write lock must be
1416  * held when this function is called.
1417  */
1418 static void
1419 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1420 {
1421     if (obj->init_scanned || obj->init_done)
1422         return;
1423     obj->init_scanned = true;
1424
1425     /* Recursively process the successor objects. */
1426     if (&obj->next != tail)
1427         initlist_add_objects(obj->next, tail, list);
1428
1429     /* Recursively process the needed objects. */
1430     if (obj->needed != NULL)
1431         initlist_add_neededs(obj->needed, list);
1432
1433     /* Add the object to the init list. */
1434     if (obj->init != (Elf_Addr)NULL)
1435         objlist_push_tail(list, obj);
1436
1437     /* Add the object to the global fini list in the reverse order. */
1438     if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1439         objlist_push_head(&list_fini, obj);
1440         obj->on_fini_list = true;
1441     }
1442 }
1443
1444 #ifndef FPTR_TARGET
1445 #define FPTR_TARGET(f)  ((Elf_Addr) (f))
1446 #endif
1447
1448 static bool
1449 is_exported(const Elf_Sym *def)
1450 {
1451     Elf_Addr value;
1452     const func_ptr_type *p;
1453
1454     value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1455     for (p = exports;  *p != NULL;  p++)
1456         if (FPTR_TARGET(*p) == value)
1457             return true;
1458     return false;
1459 }
1460
1461 /*
1462  * Given a shared object, traverse its list of needed objects, and load
1463  * each of them.  Returns 0 on success.  Generates an error message and
1464  * returns -1 on failure.
1465  */
1466 static int
1467 load_needed_objects(Obj_Entry *first, int flags)
1468 {
1469     Obj_Entry *obj, *obj1;
1470
1471     for (obj = first;  obj != NULL;  obj = obj->next) {
1472         Needed_Entry *needed;
1473
1474         for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
1475             obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1476                 flags & ~RTLD_LO_NOLOAD);
1477             if (obj1 == NULL && !ld_tracing)
1478                 return -1;
1479             if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1480                 dbg("obj %s nodelete", obj1->path);
1481                 init_dag(obj1);
1482                 ref_dag(obj1);
1483                 obj1->ref_nodel = true;
1484             }
1485         }
1486     }
1487
1488     return 0;
1489 }
1490
1491 static int
1492 load_preload_objects(void)
1493 {
1494     char *p = ld_preload;
1495     static const char delim[] = " \t:;";
1496
1497     if (p == NULL)
1498         return 0;
1499
1500     p += strspn(p, delim);
1501     while (*p != '\0') {
1502         size_t len = strcspn(p, delim);
1503         char savech;
1504
1505         savech = p[len];
1506         p[len] = '\0';
1507         if (load_object(p, NULL, 0) == NULL)
1508             return -1;  /* XXX - cleanup */
1509         p[len] = savech;
1510         p += len;
1511         p += strspn(p, delim);
1512     }
1513     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1514     return 0;
1515 }
1516
1517 /*
1518  * Load a shared object into memory, if it is not already loaded.
1519  *
1520  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1521  * on failure.
1522  */
1523 static Obj_Entry *
1524 load_object(const char *name, const Obj_Entry *refobj, int flags)
1525 {
1526     Obj_Entry *obj;
1527     int fd = -1;
1528     struct stat sb;
1529     char *path;
1530
1531     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1532         if (object_match_name(obj, name))
1533             return obj;
1534
1535     path = find_library(name, refobj);
1536     if (path == NULL)
1537         return NULL;
1538
1539     /*
1540      * If we didn't find a match by pathname, open the file and check
1541      * again by device and inode.  This avoids false mismatches caused
1542      * by multiple links or ".." in pathnames.
1543      *
1544      * To avoid a race, we open the file and use fstat() rather than
1545      * using stat().
1546      */
1547     if ((fd = open(path, O_RDONLY)) == -1) {
1548         _rtld_error("Cannot open \"%s\"", path);
1549         free(path);
1550         return NULL;
1551     }
1552     if (fstat(fd, &sb) == -1) {
1553         _rtld_error("Cannot fstat \"%s\"", path);
1554         close(fd);
1555         free(path);
1556         return NULL;
1557     }
1558     for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1559         if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1560             close(fd);
1561             break;
1562         }
1563     }
1564     if (obj != NULL) {
1565         object_add_name(obj, name);
1566         free(path);
1567         close(fd);
1568         return obj;
1569     }
1570     if (flags & RTLD_LO_NOLOAD) {
1571         free(path);
1572         return (NULL);
1573     }
1574
1575     /* First use of this object, so we must map it in */
1576     obj = do_load_object(fd, name, path, &sb, flags);
1577     if (obj == NULL)
1578         free(path);
1579     close(fd);
1580
1581     return obj;
1582 }
1583
1584 static Obj_Entry *
1585 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1586   int flags)
1587 {
1588     Obj_Entry *obj;
1589     struct statfs fs;
1590
1591     /*
1592      * but first, make sure that environment variables haven't been
1593      * used to circumvent the noexec flag on a filesystem.
1594      */
1595     if (dangerous_ld_env) {
1596         if (fstatfs(fd, &fs) != 0) {
1597             _rtld_error("Cannot fstatfs \"%s\"", path);
1598                 return NULL;
1599         }
1600         if (fs.f_flags & MNT_NOEXEC) {
1601             _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1602             return NULL;
1603         }
1604     }
1605     dbg("loading \"%s\"", path);
1606     obj = map_object(fd, path, sbp);
1607     if (obj == NULL)
1608         return NULL;
1609
1610     object_add_name(obj, name);
1611     obj->path = path;
1612     digest_dynamic(obj, 0);
1613     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1614       RTLD_LO_DLOPEN) {
1615         dbg("refusing to load non-loadable \"%s\"", obj->path);
1616         _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1617         munmap(obj->mapbase, obj->mapsize);
1618         obj_free(obj);
1619         return (NULL);
1620     }
1621
1622     *obj_tail = obj;
1623     obj_tail = &obj->next;
1624     obj_count++;
1625     obj_loads++;
1626     linkmap_add(obj);   /* for GDB & dlinfo() */
1627
1628     dbg("  %p .. %p: %s", obj->mapbase,
1629          obj->mapbase + obj->mapsize - 1, obj->path);
1630     if (obj->textrel)
1631         dbg("  WARNING: %s has impure text", obj->path);
1632     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1633         obj->path);    
1634
1635     return obj;
1636 }
1637
1638 static Obj_Entry *
1639 obj_from_addr(const void *addr)
1640 {
1641     Obj_Entry *obj;
1642
1643     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1644         if (addr < (void *) obj->mapbase)
1645             continue;
1646         if (addr < (void *) (obj->mapbase + obj->mapsize))
1647             return obj;
1648     }
1649     return NULL;
1650 }
1651
1652 /*
1653  * Call the finalization functions for each of the objects in "list"
1654  * which are unreferenced.  All of the objects are expected to have
1655  * non-NULL fini functions.
1656  */
1657 static void
1658 objlist_call_fini(Objlist *list, bool force, int *lockstate)
1659 {
1660     Objlist_Entry *elm, *elm_tmp;
1661     char *saved_msg;
1662
1663     /*
1664      * Preserve the current error message since a fini function might
1665      * call into the dynamic linker and overwrite it.
1666      */
1667     saved_msg = errmsg_save();
1668     STAILQ_FOREACH_SAFE(elm, list, link, elm_tmp) {
1669         if (elm->obj->refcount == 0 || force) {
1670             dbg("calling fini function for %s at %p", elm->obj->path,
1671                 (void *)elm->obj->fini);
1672             LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1673                 elm->obj->path);
1674             /* Remove object from fini list to prevent recursive invocation. */
1675             STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1676             wlock_release(rtld_bind_lock, *lockstate);
1677             call_initfini_pointer(elm->obj, elm->obj->fini);
1678             *lockstate = wlock_acquire(rtld_bind_lock);
1679             /* No need to free anything if process is going down. */
1680             if (!force)
1681                 free(elm);
1682         }
1683     }
1684     errmsg_restore(saved_msg);
1685 }
1686
1687 /*
1688  * Call the initialization functions for each of the objects in
1689  * "list".  All of the objects are expected to have non-NULL init
1690  * functions.
1691  */
1692 static void
1693 objlist_call_init(Objlist *list, int *lockstate)
1694 {
1695     Objlist_Entry *elm;
1696     Obj_Entry *obj;
1697     char *saved_msg;
1698
1699     /*
1700      * Clean init_scanned flag so that objects can be rechecked and
1701      * possibly initialized earlier if any of vectors called below
1702      * cause the change by using dlopen.
1703      */
1704     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1705         obj->init_scanned = false;
1706
1707     /*
1708      * Preserve the current error message since an init function might
1709      * call into the dynamic linker and overwrite it.
1710      */
1711     saved_msg = errmsg_save();
1712     STAILQ_FOREACH(elm, list, link) {
1713         if (elm->obj->init_done) /* Initialized early. */
1714             continue;
1715         dbg("calling init function for %s at %p", elm->obj->path,
1716             (void *)elm->obj->init);
1717         LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1718             elm->obj->path);
1719         /*
1720          * Race: other thread might try to use this object before current
1721          * one completes the initilization. Not much can be done here
1722          * without better locking.
1723          */
1724         elm->obj->init_done = true;
1725         wlock_release(rtld_bind_lock, *lockstate);
1726         call_initfini_pointer(elm->obj, elm->obj->init);
1727         *lockstate = wlock_acquire(rtld_bind_lock);
1728     }
1729     errmsg_restore(saved_msg);
1730 }
1731
1732 static void
1733 objlist_clear(Objlist *list)
1734 {
1735     Objlist_Entry *elm;
1736
1737     while (!STAILQ_EMPTY(list)) {
1738         elm = STAILQ_FIRST(list);
1739         STAILQ_REMOVE_HEAD(list, link);
1740         free(elm);
1741     }
1742 }
1743
1744 static Objlist_Entry *
1745 objlist_find(Objlist *list, const Obj_Entry *obj)
1746 {
1747     Objlist_Entry *elm;
1748
1749     STAILQ_FOREACH(elm, list, link)
1750         if (elm->obj == obj)
1751             return elm;
1752     return NULL;
1753 }
1754
1755 static void
1756 objlist_init(Objlist *list)
1757 {
1758     STAILQ_INIT(list);
1759 }
1760
1761 static void
1762 objlist_push_head(Objlist *list, Obj_Entry *obj)
1763 {
1764     Objlist_Entry *elm;
1765
1766     elm = NEW(Objlist_Entry);
1767     elm->obj = obj;
1768     STAILQ_INSERT_HEAD(list, elm, link);
1769 }
1770
1771 static void
1772 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1773 {
1774     Objlist_Entry *elm;
1775
1776     elm = NEW(Objlist_Entry);
1777     elm->obj = obj;
1778     STAILQ_INSERT_TAIL(list, elm, link);
1779 }
1780
1781 static void
1782 objlist_remove(Objlist *list, Obj_Entry *obj)
1783 {
1784     Objlist_Entry *elm;
1785
1786     if ((elm = objlist_find(list, obj)) != NULL) {
1787         STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1788         free(elm);
1789     }
1790 }
1791
1792 /*
1793  * Relocate newly-loaded shared objects.  The argument is a pointer to
1794  * the Obj_Entry for the first such object.  All objects from the first
1795  * to the end of the list of objects are relocated.  Returns 0 on success,
1796  * or -1 on failure.
1797  */
1798 static int
1799 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1800 {
1801     Obj_Entry *obj;
1802
1803     for (obj = first;  obj != NULL;  obj = obj->next) {
1804         if (obj != rtldobj)
1805             dbg("relocating \"%s\"", obj->path);
1806         if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1807             obj->symtab == NULL || obj->strtab == NULL) {
1808             _rtld_error("%s: Shared object has no run-time symbol table",
1809               obj->path);
1810             return -1;
1811         }
1812
1813         if (obj->textrel) {
1814             /* There are relocations to the write-protected text segment. */
1815             if (mprotect(obj->mapbase, obj->textsize,
1816               PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1817                 _rtld_error("%s: Cannot write-enable text segment: %s",
1818                   obj->path, strerror(errno));
1819                 return -1;
1820             }
1821         }
1822
1823         /* Process the non-PLT relocations. */
1824         if (reloc_non_plt(obj, rtldobj))
1825                 return -1;
1826
1827         if (obj->textrel) {     /* Re-protected the text segment. */
1828             if (mprotect(obj->mapbase, obj->textsize,
1829               PROT_READ|PROT_EXEC) == -1) {
1830                 _rtld_error("%s: Cannot write-protect text segment: %s",
1831                   obj->path, strerror(errno));
1832                 return -1;
1833             }
1834         }
1835
1836         /* Process the PLT relocations. */
1837         if (reloc_plt(obj) == -1)
1838             return -1;
1839         /* Relocate the jump slots if we are doing immediate binding. */
1840         if (obj->bind_now || bind_now)
1841             if (reloc_jmpslots(obj) == -1)
1842                 return -1;
1843
1844
1845         /*
1846          * Set up the magic number and version in the Obj_Entry.  These
1847          * were checked in the crt1.o from the original ElfKit, so we
1848          * set them for backward compatibility.
1849          */
1850         obj->magic = RTLD_MAGIC;
1851         obj->version = RTLD_VERSION;
1852
1853         /* Set the special PLT or GOT entries. */
1854         init_pltgot(obj);
1855     }
1856
1857     return 0;
1858 }
1859
1860 /*
1861  * Cleanup procedure.  It will be called (by the atexit mechanism) just
1862  * before the process exits.
1863  */
1864 static void
1865 rtld_exit(void)
1866 {
1867     int lockstate;
1868
1869     lockstate = wlock_acquire(rtld_bind_lock);
1870     dbg("rtld_exit()");
1871     objlist_call_fini(&list_fini, true, &lockstate);
1872     /* No need to remove the items from the list, since we are exiting. */
1873     if (!libmap_disable)
1874         lm_fini();
1875     wlock_release(rtld_bind_lock, lockstate);
1876 }
1877
1878 static void *
1879 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1880 {
1881 #ifdef COMPAT_32BIT
1882     const char *trans;
1883 #endif
1884     if (path == NULL)
1885         return (NULL);
1886
1887     path += strspn(path, ":;");
1888     while (*path != '\0') {
1889         size_t len;
1890         char  *res;
1891
1892         len = strcspn(path, ":;");
1893 #ifdef COMPAT_32BIT
1894         trans = lm_findn(NULL, path, len);
1895         if (trans)
1896             res = callback(trans, strlen(trans), arg);
1897         else
1898 #endif
1899         res = callback(path, len, arg);
1900
1901         if (res != NULL)
1902             return (res);
1903
1904         path += len;
1905         path += strspn(path, ":;");
1906     }
1907
1908     return (NULL);
1909 }
1910
1911 struct try_library_args {
1912     const char  *name;
1913     size_t       namelen;
1914     char        *buffer;
1915     size_t       buflen;
1916 };
1917
1918 static void *
1919 try_library_path(const char *dir, size_t dirlen, void *param)
1920 {
1921     struct try_library_args *arg;
1922
1923     arg = param;
1924     if (*dir == '/' || trust) {
1925         char *pathname;
1926
1927         if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1928                 return (NULL);
1929
1930         pathname = arg->buffer;
1931         strncpy(pathname, dir, dirlen);
1932         pathname[dirlen] = '/';
1933         strcpy(pathname + dirlen + 1, arg->name);
1934
1935         dbg("  Trying \"%s\"", pathname);
1936         if (access(pathname, F_OK) == 0) {              /* We found it */
1937             pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1938             strcpy(pathname, arg->buffer);
1939             return (pathname);
1940         }
1941     }
1942     return (NULL);
1943 }
1944
1945 static char *
1946 search_library_path(const char *name, const char *path)
1947 {
1948     char *p;
1949     struct try_library_args arg;
1950
1951     if (path == NULL)
1952         return NULL;
1953
1954     arg.name = name;
1955     arg.namelen = strlen(name);
1956     arg.buffer = xmalloc(PATH_MAX);
1957     arg.buflen = PATH_MAX;
1958
1959     p = path_enumerate(path, try_library_path, &arg);
1960
1961     free(arg.buffer);
1962
1963     return (p);
1964 }
1965
1966 int
1967 dlclose(void *handle)
1968 {
1969     Obj_Entry *root;
1970     int lockstate;
1971
1972     lockstate = wlock_acquire(rtld_bind_lock);
1973     root = dlcheck(handle);
1974     if (root == NULL) {
1975         wlock_release(rtld_bind_lock, lockstate);
1976         return -1;
1977     }
1978     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1979         root->path);
1980
1981     /* Unreference the object and its dependencies. */
1982     root->dl_refcount--;
1983
1984     unref_dag(root);
1985
1986     if (root->refcount == 0) {
1987         /*
1988          * The object is no longer referenced, so we must unload it.
1989          * First, call the fini functions.
1990          */
1991         objlist_call_fini(&list_fini, false, &lockstate);
1992
1993         /* Finish cleaning up the newly-unreferenced objects. */
1994         GDB_STATE(RT_DELETE,&root->linkmap);
1995         unload_object(root);
1996         GDB_STATE(RT_CONSISTENT,NULL);
1997     }
1998     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1999     wlock_release(rtld_bind_lock, lockstate);
2000     return 0;
2001 }
2002
2003 char *
2004 dlerror(void)
2005 {
2006     char *msg = error_message;
2007     error_message = NULL;
2008     return msg;
2009 }
2010
2011 /*
2012  * This function is deprecated and has no effect.
2013  */
2014 void
2015 dllockinit(void *context,
2016            void *(*lock_create)(void *context),
2017            void (*rlock_acquire)(void *lock),
2018            void (*wlock_acquire)(void *lock),
2019            void (*lock_release)(void *lock),
2020            void (*lock_destroy)(void *lock),
2021            void (*context_destroy)(void *context))
2022 {
2023     static void *cur_context;
2024     static void (*cur_context_destroy)(void *);
2025
2026     /* Just destroy the context from the previous call, if necessary. */
2027     if (cur_context_destroy != NULL)
2028         cur_context_destroy(cur_context);
2029     cur_context = context;
2030     cur_context_destroy = context_destroy;
2031 }
2032
2033 void *
2034 dlopen(const char *name, int mode)
2035 {
2036     Obj_Entry **old_obj_tail;
2037     Obj_Entry *obj;
2038     Objlist initlist;
2039     int result, lockstate, nodelete, lo_flags;
2040
2041     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2042     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2043     if (ld_tracing != NULL)
2044         environ = (char **)*get_program_var_addr("environ");
2045     nodelete = mode & RTLD_NODELETE;
2046     lo_flags = RTLD_LO_DLOPEN;
2047     if (mode & RTLD_NOLOAD)
2048             lo_flags |= RTLD_LO_NOLOAD;
2049     if (ld_tracing != NULL)
2050             lo_flags |= RTLD_LO_TRACE;
2051
2052     objlist_init(&initlist);
2053
2054     lockstate = wlock_acquire(rtld_bind_lock);
2055     GDB_STATE(RT_ADD,NULL);
2056
2057     old_obj_tail = obj_tail;
2058     obj = NULL;
2059     if (name == NULL) {
2060         obj = obj_main;
2061         obj->refcount++;
2062     } else {
2063         obj = load_object(name, obj_main, lo_flags);
2064     }
2065
2066     if (obj) {
2067         obj->dl_refcount++;
2068         if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2069             objlist_push_tail(&list_global, obj);
2070         mode &= RTLD_MODEMASK;
2071         if (*old_obj_tail != NULL) {            /* We loaded something new. */
2072             assert(*old_obj_tail == obj);
2073             result = load_needed_objects(obj, RTLD_LO_DLOPEN);
2074             init_dag(obj);
2075             if (result != -1)
2076                 result = rtld_verify_versions(&obj->dagmembers);
2077             if (result != -1 && ld_tracing)
2078                 goto trace;
2079             if (result == -1 ||
2080               (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
2081                 obj->dl_refcount--;
2082                 unref_dag(obj);
2083                 if (obj->refcount == 0)
2084                     unload_object(obj);
2085                 obj = NULL;
2086             } else {
2087                 /* Make list of init functions to call. */
2088                 initlist_add_objects(obj, &obj->next, &initlist);
2089             }
2090         } else {
2091
2092             /* Bump the reference counts for objects on this DAG. */
2093             ref_dag(obj);
2094
2095             if (ld_tracing)
2096                 goto trace;
2097         }
2098         if (obj != NULL && (nodelete || obj->z_nodelete) && !obj->ref_nodel) {
2099             dbg("obj %s nodelete", obj->path);
2100             ref_dag(obj);
2101             obj->z_nodelete = obj->ref_nodel = true;
2102         }
2103     }
2104
2105     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2106         name);
2107     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2108
2109     /* Call the init functions. */
2110     objlist_call_init(&initlist, &lockstate);
2111     objlist_clear(&initlist);
2112     wlock_release(rtld_bind_lock, lockstate);
2113     return obj;
2114 trace:
2115     trace_loaded_objects(obj);
2116     wlock_release(rtld_bind_lock, lockstate);
2117     exit(0);
2118 }
2119
2120 static void *
2121 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2122     int flags)
2123 {
2124     DoneList donelist;
2125     const Obj_Entry *obj, *defobj;
2126     const Elf_Sym *def, *symp;
2127     unsigned long hash;
2128     int lockstate;
2129
2130     hash = elf_hash(name);
2131     def = NULL;
2132     defobj = NULL;
2133     flags |= SYMLOOK_IN_PLT;
2134
2135     lockstate = rlock_acquire(rtld_bind_lock);
2136     if (handle == NULL || handle == RTLD_NEXT ||
2137         handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2138
2139         if ((obj = obj_from_addr(retaddr)) == NULL) {
2140             _rtld_error("Cannot determine caller's shared object");
2141             rlock_release(rtld_bind_lock, lockstate);
2142             return NULL;
2143         }
2144         if (handle == NULL) {   /* Just the caller's shared object. */
2145             def = symlook_obj(name, hash, obj, ve, flags);
2146             defobj = obj;
2147         } else if (handle == RTLD_NEXT || /* Objects after caller's */
2148                    handle == RTLD_SELF) { /* ... caller included */
2149             if (handle == RTLD_NEXT)
2150                 obj = obj->next;
2151             for (; obj != NULL; obj = obj->next) {
2152                 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
2153                     if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2154                         def = symp;
2155                         defobj = obj;
2156                         if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2157                             break;
2158                     }
2159                 }
2160             }
2161             /*
2162              * Search the dynamic linker itself, and possibly resolve the
2163              * symbol from there.  This is how the application links to
2164              * dynamic linker services such as dlopen.  Only the values listed
2165              * in the "exports" array can be resolved from the dynamic linker.
2166              */
2167             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2168                 symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
2169                 if (symp != NULL && is_exported(symp)) {
2170                     def = symp;
2171                     defobj = &obj_rtld;
2172                 }
2173             }
2174         } else {
2175             assert(handle == RTLD_DEFAULT);
2176             def = symlook_default(name, hash, obj, &defobj, ve, flags);
2177         }
2178     } else {
2179         if ((obj = dlcheck(handle)) == NULL) {
2180             rlock_release(rtld_bind_lock, lockstate);
2181             return NULL;
2182         }
2183
2184         donelist_init(&donelist);
2185         if (obj->mainprog) {
2186             /* Search main program and all libraries loaded by it. */
2187             def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
2188                                &donelist);
2189
2190             /*
2191              * We do not distinguish between 'main' object and global scope.
2192              * If symbol is not defined by objects loaded at startup, continue
2193              * search among dynamically loaded objects with RTLD_GLOBAL
2194              * scope.
2195              */
2196             if (def == NULL)
2197                 def = symlook_list(name, hash, &list_global, &defobj, ve,
2198                                     flags, &donelist);
2199         } else {
2200             Needed_Entry fake;
2201
2202             /* Search the whole DAG rooted at the given object. */
2203             fake.next = NULL;
2204             fake.obj = (Obj_Entry *)obj;
2205             fake.name = 0;
2206             def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
2207                                  &donelist);
2208         }
2209     }
2210
2211     if (def != NULL) {
2212         rlock_release(rtld_bind_lock, lockstate);
2213
2214         /*
2215          * The value required by the caller is derived from the value
2216          * of the symbol. For the ia64 architecture, we need to
2217          * construct a function descriptor which the caller can use to
2218          * call the function with the right 'gp' value. For other
2219          * architectures and for non-functions, the value is simply
2220          * the relocated value of the symbol.
2221          */
2222         if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2223             return make_function_pointer(def, defobj);
2224         else
2225             return defobj->relocbase + def->st_value;
2226     }
2227
2228     _rtld_error("Undefined symbol \"%s\"", name);
2229     rlock_release(rtld_bind_lock, lockstate);
2230     return NULL;
2231 }
2232
2233 void *
2234 dlsym(void *handle, const char *name)
2235 {
2236         return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2237             SYMLOOK_DLSYM);
2238 }
2239
2240 dlfunc_t
2241 dlfunc(void *handle, const char *name)
2242 {
2243         union {
2244                 void *d;
2245                 dlfunc_t f;
2246         } rv;
2247
2248         rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2249             SYMLOOK_DLSYM);
2250         return (rv.f);
2251 }
2252
2253 void *
2254 dlvsym(void *handle, const char *name, const char *version)
2255 {
2256         Ver_Entry ventry;
2257
2258         ventry.name = version;
2259         ventry.file = NULL;
2260         ventry.hash = elf_hash(version);
2261         ventry.flags= 0;
2262         return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2263             SYMLOOK_DLSYM);
2264 }
2265
2266 int
2267 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2268 {
2269     const Obj_Entry *obj;
2270     int lockstate;
2271
2272     lockstate = rlock_acquire(rtld_bind_lock);
2273     obj = obj_from_addr(addr);
2274     if (obj == NULL) {
2275         _rtld_error("No shared object contains address");
2276         rlock_release(rtld_bind_lock, lockstate);
2277         return (0);
2278     }
2279     rtld_fill_dl_phdr_info(obj, phdr_info);
2280     rlock_release(rtld_bind_lock, lockstate);
2281     return (1);
2282 }
2283
2284 int
2285 dladdr(const void *addr, Dl_info *info)
2286 {
2287     const Obj_Entry *obj;
2288     const Elf_Sym *def;
2289     void *symbol_addr;
2290     unsigned long symoffset;
2291     int lockstate;
2292
2293     lockstate = rlock_acquire(rtld_bind_lock);
2294     obj = obj_from_addr(addr);
2295     if (obj == NULL) {
2296         _rtld_error("No shared object contains address");
2297         rlock_release(rtld_bind_lock, lockstate);
2298         return 0;
2299     }
2300     info->dli_fname = obj->path;
2301     info->dli_fbase = obj->mapbase;
2302     info->dli_saddr = (void *)0;
2303     info->dli_sname = NULL;
2304
2305     /*
2306      * Walk the symbol list looking for the symbol whose address is
2307      * closest to the address sent in.
2308      */
2309     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2310         def = obj->symtab + symoffset;
2311
2312         /*
2313          * For skip the symbol if st_shndx is either SHN_UNDEF or
2314          * SHN_COMMON.
2315          */
2316         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2317             continue;
2318
2319         /*
2320          * If the symbol is greater than the specified address, or if it
2321          * is further away from addr than the current nearest symbol,
2322          * then reject it.
2323          */
2324         symbol_addr = obj->relocbase + def->st_value;
2325         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2326             continue;
2327
2328         /* Update our idea of the nearest symbol. */
2329         info->dli_sname = obj->strtab + def->st_name;
2330         info->dli_saddr = symbol_addr;
2331
2332         /* Exact match? */
2333         if (info->dli_saddr == addr)
2334             break;
2335     }
2336     rlock_release(rtld_bind_lock, lockstate);
2337     return 1;
2338 }
2339
2340 int
2341 dlinfo(void *handle, int request, void *p)
2342 {
2343     const Obj_Entry *obj;
2344     int error, lockstate;
2345
2346     lockstate = rlock_acquire(rtld_bind_lock);
2347
2348     if (handle == NULL || handle == RTLD_SELF) {
2349         void *retaddr;
2350
2351         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
2352         if ((obj = obj_from_addr(retaddr)) == NULL)
2353             _rtld_error("Cannot determine caller's shared object");
2354     } else
2355         obj = dlcheck(handle);
2356
2357     if (obj == NULL) {
2358         rlock_release(rtld_bind_lock, lockstate);
2359         return (-1);
2360     }
2361
2362     error = 0;
2363     switch (request) {
2364     case RTLD_DI_LINKMAP:
2365         *((struct link_map const **)p) = &obj->linkmap;
2366         break;
2367     case RTLD_DI_ORIGIN:
2368         error = rtld_dirname(obj->path, p);
2369         break;
2370
2371     case RTLD_DI_SERINFOSIZE:
2372     case RTLD_DI_SERINFO:
2373         error = do_search_info(obj, request, (struct dl_serinfo *)p);
2374         break;
2375
2376     default:
2377         _rtld_error("Invalid request %d passed to dlinfo()", request);
2378         error = -1;
2379     }
2380
2381     rlock_release(rtld_bind_lock, lockstate);
2382
2383     return (error);
2384 }
2385
2386 static void
2387 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2388 {
2389
2390         phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2391         phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2392             STAILQ_FIRST(&obj->names)->name : obj->path;
2393         phdr_info->dlpi_phdr = obj->phdr;
2394         phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2395         phdr_info->dlpi_tls_modid = obj->tlsindex;
2396         phdr_info->dlpi_tls_data = obj->tlsinit;
2397         phdr_info->dlpi_adds = obj_loads;
2398         phdr_info->dlpi_subs = obj_loads - obj_count;
2399 }
2400
2401 int
2402 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2403 {
2404     struct dl_phdr_info phdr_info;
2405     const Obj_Entry *obj;
2406     int error, bind_lockstate, phdr_lockstate;
2407
2408     phdr_lockstate = wlock_acquire(rtld_phdr_lock);
2409     bind_lockstate = rlock_acquire(rtld_bind_lock);
2410
2411     error = 0;
2412
2413     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2414         rtld_fill_dl_phdr_info(obj, &phdr_info);
2415         if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2416                 break;
2417
2418     }
2419     rlock_release(rtld_bind_lock, bind_lockstate);
2420     wlock_release(rtld_phdr_lock, phdr_lockstate);
2421
2422     return (error);
2423 }
2424
2425 struct fill_search_info_args {
2426     int          request;
2427     unsigned int flags;
2428     Dl_serinfo  *serinfo;
2429     Dl_serpath  *serpath;
2430     char        *strspace;
2431 };
2432
2433 static void *
2434 fill_search_info(const char *dir, size_t dirlen, void *param)
2435 {
2436     struct fill_search_info_args *arg;
2437
2438     arg = param;
2439
2440     if (arg->request == RTLD_DI_SERINFOSIZE) {
2441         arg->serinfo->dls_cnt ++;
2442         arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2443     } else {
2444         struct dl_serpath *s_entry;
2445
2446         s_entry = arg->serpath;
2447         s_entry->dls_name  = arg->strspace;
2448         s_entry->dls_flags = arg->flags;
2449
2450         strncpy(arg->strspace, dir, dirlen);
2451         arg->strspace[dirlen] = '\0';
2452
2453         arg->strspace += dirlen + 1;
2454         arg->serpath++;
2455     }
2456
2457     return (NULL);
2458 }
2459
2460 static int
2461 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2462 {
2463     struct dl_serinfo _info;
2464     struct fill_search_info_args args;
2465
2466     args.request = RTLD_DI_SERINFOSIZE;
2467     args.serinfo = &_info;
2468
2469     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2470     _info.dls_cnt  = 0;
2471
2472     path_enumerate(ld_library_path, fill_search_info, &args);
2473     path_enumerate(obj->rpath, fill_search_info, &args);
2474     path_enumerate(gethints(), fill_search_info, &args);
2475     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2476
2477
2478     if (request == RTLD_DI_SERINFOSIZE) {
2479         info->dls_size = _info.dls_size;
2480         info->dls_cnt = _info.dls_cnt;
2481         return (0);
2482     }
2483
2484     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2485         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2486         return (-1);
2487     }
2488
2489     args.request  = RTLD_DI_SERINFO;
2490     args.serinfo  = info;
2491     args.serpath  = &info->dls_serpath[0];
2492     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2493
2494     args.flags = LA_SER_LIBPATH;
2495     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2496         return (-1);
2497
2498     args.flags = LA_SER_RUNPATH;
2499     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2500         return (-1);
2501
2502     args.flags = LA_SER_CONFIG;
2503     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2504         return (-1);
2505
2506     args.flags = LA_SER_DEFAULT;
2507     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2508         return (-1);
2509     return (0);
2510 }
2511
2512 static int
2513 rtld_dirname(const char *path, char *bname)
2514 {
2515     const char *endp;
2516
2517     /* Empty or NULL string gets treated as "." */
2518     if (path == NULL || *path == '\0') {
2519         bname[0] = '.';
2520         bname[1] = '\0';
2521         return (0);
2522     }
2523
2524     /* Strip trailing slashes */
2525     endp = path + strlen(path) - 1;
2526     while (endp > path && *endp == '/')
2527         endp--;
2528
2529     /* Find the start of the dir */
2530     while (endp > path && *endp != '/')
2531         endp--;
2532
2533     /* Either the dir is "/" or there are no slashes */
2534     if (endp == path) {
2535         bname[0] = *endp == '/' ? '/' : '.';
2536         bname[1] = '\0';
2537         return (0);
2538     } else {
2539         do {
2540             endp--;
2541         } while (endp > path && *endp == '/');
2542     }
2543
2544     if (endp - path + 2 > PATH_MAX)
2545     {
2546         _rtld_error("Filename is too long: %s", path);
2547         return(-1);
2548     }
2549
2550     strncpy(bname, path, endp - path + 1);
2551     bname[endp - path + 1] = '\0';
2552     return (0);
2553 }
2554
2555 static int
2556 rtld_dirname_abs(const char *path, char *base)
2557 {
2558         char base_rel[PATH_MAX];
2559
2560         if (rtld_dirname(path, base) == -1)
2561                 return (-1);
2562         if (base[0] == '/')
2563                 return (0);
2564         if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2565             strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2566             strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2567                 return (-1);
2568         strcpy(base, base_rel);
2569         return (0);
2570 }
2571
2572 static void
2573 linkmap_add(Obj_Entry *obj)
2574 {
2575     struct link_map *l = &obj->linkmap;
2576     struct link_map *prev;
2577
2578     obj->linkmap.l_name = obj->path;
2579     obj->linkmap.l_addr = obj->mapbase;
2580     obj->linkmap.l_ld = obj->dynamic;
2581 #ifdef __mips__
2582     /* GDB needs load offset on MIPS to use the symbols */
2583     obj->linkmap.l_offs = obj->relocbase;
2584 #endif
2585
2586     if (r_debug.r_map == NULL) {
2587         r_debug.r_map = l;
2588         return;
2589     }
2590
2591     /*
2592      * Scan to the end of the list, but not past the entry for the
2593      * dynamic linker, which we want to keep at the very end.
2594      */
2595     for (prev = r_debug.r_map;
2596       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2597       prev = prev->l_next)
2598         ;
2599
2600     /* Link in the new entry. */
2601     l->l_prev = prev;
2602     l->l_next = prev->l_next;
2603     if (l->l_next != NULL)
2604         l->l_next->l_prev = l;
2605     prev->l_next = l;
2606 }
2607
2608 static void
2609 linkmap_delete(Obj_Entry *obj)
2610 {
2611     struct link_map *l = &obj->linkmap;
2612
2613     if (l->l_prev == NULL) {
2614         if ((r_debug.r_map = l->l_next) != NULL)
2615             l->l_next->l_prev = NULL;
2616         return;
2617     }
2618
2619     if ((l->l_prev->l_next = l->l_next) != NULL)
2620         l->l_next->l_prev = l->l_prev;
2621 }
2622
2623 /*
2624  * Function for the debugger to set a breakpoint on to gain control.
2625  *
2626  * The two parameters allow the debugger to easily find and determine
2627  * what the runtime loader is doing and to whom it is doing it.
2628  *
2629  * When the loadhook trap is hit (r_debug_state, set at program
2630  * initialization), the arguments can be found on the stack:
2631  *
2632  *  +8   struct link_map *m
2633  *  +4   struct r_debug  *rd
2634  *  +0   RetAddr
2635  */
2636 void
2637 r_debug_state(struct r_debug* rd, struct link_map *m)
2638 {
2639 }
2640
2641 /*
2642  * Get address of the pointer variable in the main program.
2643  */
2644 static const void **
2645 get_program_var_addr(const char *name)
2646 {
2647     const Obj_Entry *obj;
2648     unsigned long hash;
2649
2650     hash = elf_hash(name);
2651     for (obj = obj_main;  obj != NULL;  obj = obj->next) {
2652         const Elf_Sym *def;
2653
2654         if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2655             const void **addr;
2656
2657             addr = (const void **)(obj->relocbase + def->st_value);
2658             return addr;
2659         }
2660     }
2661     return NULL;
2662 }
2663
2664 /*
2665  * Set a pointer variable in the main program to the given value.  This
2666  * is used to set key variables such as "environ" before any of the
2667  * init functions are called.
2668  */
2669 static void
2670 set_program_var(const char *name, const void *value)
2671 {
2672     const void **addr;
2673
2674     if ((addr = get_program_var_addr(name)) != NULL) {
2675         dbg("\"%s\": *%p <-- %p", name, addr, value);
2676         *addr = value;
2677     }
2678 }
2679
2680 /*
2681  * Given a symbol name in a referencing object, find the corresponding
2682  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
2683  * no definition was found.  Returns a pointer to the Obj_Entry of the
2684  * defining object via the reference parameter DEFOBJ_OUT.
2685  */
2686 static const Elf_Sym *
2687 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2688     const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2689 {
2690     DoneList donelist;
2691     const Elf_Sym *def;
2692     const Elf_Sym *symp;
2693     const Obj_Entry *obj;
2694     const Obj_Entry *defobj;
2695     const Objlist_Entry *elm;
2696     def = NULL;
2697     defobj = NULL;
2698     donelist_init(&donelist);
2699
2700     /* Look first in the referencing object if linked symbolically. */
2701     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2702         symp = symlook_obj(name, hash, refobj, ventry, flags);
2703         if (symp != NULL) {
2704             def = symp;
2705             defobj = refobj;
2706         }
2707     }
2708
2709     /* Search all objects loaded at program start up. */
2710     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2711         symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2712             &donelist);
2713         if (symp != NULL &&
2714           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2715             def = symp;
2716             defobj = obj;
2717         }
2718     }
2719
2720     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2721     STAILQ_FOREACH(elm, &list_global, link) {
2722        if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2723            break;
2724        symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2725            flags, &donelist);
2726         if (symp != NULL &&
2727           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2728             def = symp;
2729             defobj = obj;
2730         }
2731     }
2732
2733     /* Search all dlopened DAGs containing the referencing object. */
2734     STAILQ_FOREACH(elm, &refobj->dldags, link) {
2735         if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2736             break;
2737         symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2738             flags, &donelist);
2739         if (symp != NULL &&
2740           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2741             def = symp;
2742             defobj = obj;
2743         }
2744     }
2745
2746     /*
2747      * Search the dynamic linker itself, and possibly resolve the
2748      * symbol from there.  This is how the application links to
2749      * dynamic linker services such as dlopen.  Only the values listed
2750      * in the "exports" array can be resolved from the dynamic linker.
2751      */
2752     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2753         symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2754         if (symp != NULL && is_exported(symp)) {
2755             def = symp;
2756             defobj = &obj_rtld;
2757         }
2758     }
2759
2760     if (def != NULL)
2761         *defobj_out = defobj;
2762     return def;
2763 }
2764
2765 static const Elf_Sym *
2766 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2767   const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2768   DoneList *dlp)
2769 {
2770     const Elf_Sym *symp;
2771     const Elf_Sym *def;
2772     const Obj_Entry *defobj;
2773     const Objlist_Entry *elm;
2774
2775     def = NULL;
2776     defobj = NULL;
2777     STAILQ_FOREACH(elm, objlist, link) {
2778         if (donelist_check(dlp, elm->obj))
2779             continue;
2780         if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2781             if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2782                 def = symp;
2783                 defobj = elm->obj;
2784                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2785                     break;
2786             }
2787         }
2788     }
2789     if (def != NULL)
2790         *defobj_out = defobj;
2791     return def;
2792 }
2793
2794 /*
2795  * Search the symbol table of a shared object and all objects needed
2796  * by it for a symbol of the given name.  Search order is
2797  * breadth-first.  Returns a pointer to the symbol, or NULL if no
2798  * definition was found.
2799  */
2800 static const Elf_Sym *
2801 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2802   const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2803   DoneList *dlp)
2804 {
2805     const Elf_Sym *def, *def_w;
2806     const Needed_Entry *n;
2807     const Obj_Entry *obj, *defobj, *defobj1;
2808
2809     def = def_w = NULL;
2810     defobj = NULL;
2811     for (n = needed; n != NULL; n = n->next) {
2812         if ((obj = n->obj) == NULL ||
2813             donelist_check(dlp, obj) ||
2814             (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2815             continue;
2816         defobj = obj;
2817         if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2818             *defobj_out = defobj;
2819             return (def);
2820         }
2821     }
2822     /*
2823      * There we come when either symbol definition is not found in
2824      * directly needed objects, or found symbol is weak.
2825      */
2826     for (n = needed; n != NULL; n = n->next) {
2827         if ((obj = n->obj) == NULL)
2828             continue;
2829         def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2830                                ventry, flags, dlp);
2831         if (def_w == NULL)
2832             continue;
2833         if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2834             def = def_w;
2835             defobj = defobj1;
2836         }
2837         if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2838             break;
2839     }
2840     if (def != NULL)
2841         *defobj_out = defobj;
2842     return (def);
2843 }
2844
2845 /*
2846  * Search the symbol table of a single shared object for a symbol of
2847  * the given name and version, if requested.  Returns a pointer to the
2848  * symbol, or NULL if no definition was found.
2849  *
2850  * The symbol's hash value is passed in for efficiency reasons; that
2851  * eliminates many recomputations of the hash value.
2852  */
2853 const Elf_Sym *
2854 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2855     const Ver_Entry *ventry, int flags)
2856 {
2857     unsigned long symnum;
2858     const Elf_Sym *vsymp;
2859     Elf_Versym verndx;
2860     int vcount;
2861
2862     if (obj->buckets == NULL)
2863         return NULL;
2864
2865     vsymp = NULL;
2866     vcount = 0;
2867     symnum = obj->buckets[hash % obj->nbuckets];
2868
2869     for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2870         const Elf_Sym *symp;
2871         const char *strp;
2872
2873         if (symnum >= obj->nchains)
2874                 return NULL;    /* Bad object */
2875
2876         symp = obj->symtab + symnum;
2877         strp = obj->strtab + symp->st_name;
2878
2879         switch (ELF_ST_TYPE(symp->st_info)) {
2880         case STT_FUNC:
2881         case STT_NOTYPE:
2882         case STT_OBJECT:
2883             if (symp->st_value == 0)
2884                 continue;
2885                 /* fallthrough */
2886         case STT_TLS:
2887             if (symp->st_shndx != SHN_UNDEF)
2888                 break;
2889 #ifndef __mips__
2890             else if (((flags & SYMLOOK_IN_PLT) == 0) &&
2891                  (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2892                 break;
2893                 /* fallthrough */
2894 #endif
2895         default:
2896             continue;
2897         }
2898         if (name[0] != strp[0] || strcmp(name, strp) != 0)
2899             continue;
2900
2901         if (ventry == NULL) {
2902             if (obj->versyms != NULL) {
2903                 verndx = VER_NDX(obj->versyms[symnum]);
2904                 if (verndx > obj->vernum) {
2905                     _rtld_error("%s: symbol %s references wrong version %d",
2906                         obj->path, obj->strtab + symnum, verndx);
2907                     continue;
2908                 }
2909                 /*
2910                  * If we are not called from dlsym (i.e. this is a normal
2911                  * relocation from unversioned binary, accept the symbol
2912                  * immediately if it happens to have first version after
2913                  * this shared object became versioned. Otherwise, if
2914                  * symbol is versioned and not hidden, remember it. If it
2915                  * is the only symbol with this name exported by the
2916                  * shared object, it will be returned as a match at the
2917                  * end of the function. If symbol is global (verndx < 2)
2918                  * accept it unconditionally.
2919                  */
2920                 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2921                     return symp;
2922                 else if (verndx >= VER_NDX_GIVEN) {
2923                     if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2924                         if (vsymp == NULL)
2925                             vsymp = symp;
2926                         vcount ++;
2927                     }
2928                     continue;
2929                 }
2930             }
2931             return symp;
2932         } else {
2933             if (obj->versyms == NULL) {
2934                 if (object_match_name(obj, ventry->name)) {
2935                     _rtld_error("%s: object %s should provide version %s for "
2936                         "symbol %s", obj_rtld.path, obj->path, ventry->name,
2937                         obj->strtab + symnum);
2938                     continue;
2939                 }
2940             } else {
2941                 verndx = VER_NDX(obj->versyms[symnum]);
2942                 if (verndx > obj->vernum) {
2943                     _rtld_error("%s: symbol %s references wrong version %d",
2944                         obj->path, obj->strtab + symnum, verndx);
2945                     continue;
2946                 }
2947                 if (obj->vertab[verndx].hash != ventry->hash ||
2948                     strcmp(obj->vertab[verndx].name, ventry->name)) {
2949                     /*
2950                      * Version does not match. Look if this is a global symbol
2951                      * and if it is not hidden. If global symbol (verndx < 2)
2952                      * is available, use it. Do not return symbol if we are
2953                      * called by dlvsym, because dlvsym looks for a specific
2954                      * version and default one is not what dlvsym wants.
2955                      */
2956                     if ((flags & SYMLOOK_DLSYM) ||
2957                         (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2958                         (verndx >= VER_NDX_GIVEN))
2959                         continue;
2960                 }
2961             }
2962             return symp;
2963         }
2964     }
2965     return (vcount == 1) ? vsymp : NULL;
2966 }
2967
2968 static void
2969 trace_loaded_objects(Obj_Entry *obj)
2970 {
2971     char        *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2972     int         c;
2973
2974     if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2975         main_local = "";
2976
2977     if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2978         fmt1 = "\t%o => %p (%x)\n";
2979
2980     if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2981         fmt2 = "\t%o (%x)\n";
2982
2983     list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2984
2985     for (; obj; obj = obj->next) {
2986         Needed_Entry            *needed;
2987         char                    *name, *path;
2988         bool                    is_lib;
2989
2990         if (list_containers && obj->needed != NULL)
2991             printf("%s:\n", obj->path);
2992         for (needed = obj->needed; needed; needed = needed->next) {
2993             if (needed->obj != NULL) {
2994                 if (needed->obj->traced && !list_containers)
2995                     continue;
2996                 needed->obj->traced = true;
2997                 path = needed->obj->path;
2998             } else
2999                 path = "not found";
3000
3001             name = (char *)obj->strtab + needed->name;
3002             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
3003
3004             fmt = is_lib ? fmt1 : fmt2;
3005             while ((c = *fmt++) != '\0') {
3006                 switch (c) {
3007                 default:
3008                     putchar(c);
3009                     continue;
3010                 case '\\':
3011                     switch (c = *fmt) {
3012                     case '\0':
3013                         continue;
3014                     case 'n':
3015                         putchar('\n');
3016                         break;
3017                     case 't':
3018                         putchar('\t');
3019                         break;
3020                     }
3021                     break;
3022                 case '%':
3023                     switch (c = *fmt) {
3024                     case '\0':
3025                         continue;
3026                     case '%':
3027                     default:
3028                         putchar(c);
3029                         break;
3030                     case 'A':
3031                         printf("%s", main_local);
3032                         break;
3033                     case 'a':
3034                         printf("%s", obj_main->path);
3035                         break;
3036                     case 'o':
3037                         printf("%s", name);
3038                         break;
3039 #if 0
3040                     case 'm':
3041                         printf("%d", sodp->sod_major);
3042                         break;
3043                     case 'n':
3044                         printf("%d", sodp->sod_minor);
3045                         break;
3046 #endif
3047                     case 'p':
3048                         printf("%s", path);
3049                         break;
3050                     case 'x':
3051                         printf("%p", needed->obj ? needed->obj->mapbase : 0);
3052                         break;
3053                     }
3054                     break;
3055                 }
3056                 ++fmt;
3057             }
3058         }
3059     }
3060 }
3061
3062 /*
3063  * Unload a dlopened object and its dependencies from memory and from
3064  * our data structures.  It is assumed that the DAG rooted in the
3065  * object has already been unreferenced, and that the object has a
3066  * reference count of 0.
3067  */
3068 static void
3069 unload_object(Obj_Entry *root)
3070 {
3071     Obj_Entry *obj;
3072     Obj_Entry **linkp;
3073
3074     assert(root->refcount == 0);
3075
3076     /*
3077      * Pass over the DAG removing unreferenced objects from
3078      * appropriate lists.
3079      */
3080     unlink_object(root);
3081
3082     /* Unmap all objects that are no longer referenced. */
3083     linkp = &obj_list->next;
3084     while ((obj = *linkp) != NULL) {
3085         if (obj->refcount == 0) {
3086             LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3087                 obj->path);
3088             dbg("unloading \"%s\"", obj->path);
3089             munmap(obj->mapbase, obj->mapsize);
3090             linkmap_delete(obj);
3091             *linkp = obj->next;
3092             obj_count--;
3093             obj_free(obj);
3094         } else
3095             linkp = &obj->next;
3096     }
3097     obj_tail = linkp;
3098 }
3099
3100 static void
3101 unlink_object(Obj_Entry *root)
3102 {
3103     Objlist_Entry *elm;
3104
3105     if (root->refcount == 0) {
3106         /* Remove the object from the RTLD_GLOBAL list. */
3107         objlist_remove(&list_global, root);
3108
3109         /* Remove the object from all objects' DAG lists. */
3110         STAILQ_FOREACH(elm, &root->dagmembers, link) {
3111             objlist_remove(&elm->obj->dldags, root);
3112             if (elm->obj != root)
3113                 unlink_object(elm->obj);
3114         }
3115     }
3116 }
3117
3118 static void
3119 ref_dag(Obj_Entry *root)
3120 {
3121     Objlist_Entry *elm;
3122
3123     STAILQ_FOREACH(elm, &root->dagmembers, link)
3124         elm->obj->refcount++;
3125 }
3126
3127 static void
3128 unref_dag(Obj_Entry *root)
3129 {
3130     Objlist_Entry *elm;
3131
3132     STAILQ_FOREACH(elm, &root->dagmembers, link)
3133         elm->obj->refcount--;
3134 }
3135
3136 /*
3137  * Common code for MD __tls_get_addr().
3138  */
3139 void *
3140 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3141 {
3142     Elf_Addr* dtv = *dtvp;
3143     int lockstate;
3144
3145     /* Check dtv generation in case new modules have arrived */
3146     if (dtv[0] != tls_dtv_generation) {
3147         Elf_Addr* newdtv;
3148         int to_copy;
3149
3150         lockstate = wlock_acquire(rtld_bind_lock);
3151         newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3152         to_copy = dtv[1];
3153         if (to_copy > tls_max_index)
3154             to_copy = tls_max_index;
3155         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3156         newdtv[0] = tls_dtv_generation;
3157         newdtv[1] = tls_max_index;
3158         free(dtv);
3159         wlock_release(rtld_bind_lock, lockstate);
3160         *dtvp = newdtv;
3161     }
3162
3163     /* Dynamically allocate module TLS if necessary */
3164     if (!dtv[index + 1]) {
3165         /* Signal safe, wlock will block out signals. */
3166         lockstate = wlock_acquire(rtld_bind_lock);
3167         if (!dtv[index + 1])
3168             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3169         wlock_release(rtld_bind_lock, lockstate);
3170     }
3171     return (void*) (dtv[index + 1] + offset);
3172 }
3173
3174 /* XXX not sure what variants to use for arm. */
3175
3176 #if defined(__ia64__) || defined(__powerpc__)
3177
3178 /*
3179  * Allocate Static TLS using the Variant I method.
3180  */
3181 void *
3182 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3183 {
3184     Obj_Entry *obj;
3185     char *tcb;
3186     Elf_Addr **tls;
3187     Elf_Addr *dtv;
3188     Elf_Addr addr;
3189     int i;
3190
3191     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3192         return (oldtcb);
3193
3194     assert(tcbsize >= TLS_TCB_SIZE);
3195     tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3196     tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3197
3198     if (oldtcb != NULL) {
3199         memcpy(tls, oldtcb, tls_static_space);
3200         free(oldtcb);
3201
3202         /* Adjust the DTV. */
3203         dtv = tls[0];
3204         for (i = 0; i < dtv[1]; i++) {
3205             if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3206                 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3207                 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3208             }
3209         }
3210     } else {
3211         dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3212         tls[0] = dtv;
3213         dtv[0] = tls_dtv_generation;
3214         dtv[1] = tls_max_index;
3215
3216         for (obj = objs; obj; obj = obj->next) {
3217             if (obj->tlsoffset > 0) {
3218                 addr = (Elf_Addr)tls + obj->tlsoffset;
3219                 if (obj->tlsinitsize > 0)
3220                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3221                 if (obj->tlssize > obj->tlsinitsize)
3222                     memset((void*) (addr + obj->tlsinitsize), 0,
3223                            obj->tlssize - obj->tlsinitsize);
3224                 dtv[obj->tlsindex + 1] = addr;
3225             }
3226         }
3227     }
3228
3229     return (tcb);
3230 }
3231
3232 void
3233 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3234 {
3235     Elf_Addr *dtv;
3236     Elf_Addr tlsstart, tlsend;
3237     int dtvsize, i;
3238
3239     assert(tcbsize >= TLS_TCB_SIZE);
3240
3241     tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3242     tlsend = tlsstart + tls_static_space;
3243
3244     dtv = *(Elf_Addr **)tlsstart;
3245     dtvsize = dtv[1];
3246     for (i = 0; i < dtvsize; i++) {
3247         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3248             free((void*)dtv[i+2]);
3249         }
3250     }
3251     free(dtv);
3252     free(tcb);
3253 }
3254
3255 #endif
3256
3257 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3258     defined(__arm__) || defined(__mips__)
3259
3260 /*
3261  * Allocate Static TLS using the Variant II method.
3262  */
3263 void *
3264 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3265 {
3266     Obj_Entry *obj;
3267     size_t size;
3268     char *tls;
3269     Elf_Addr *dtv, *olddtv;
3270     Elf_Addr segbase, oldsegbase, addr;
3271     int i;
3272
3273     size = round(tls_static_space, tcbalign);
3274
3275     assert(tcbsize >= 2*sizeof(Elf_Addr));
3276     tls = calloc(1, size + tcbsize);
3277     dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3278
3279     segbase = (Elf_Addr)(tls + size);
3280     ((Elf_Addr*)segbase)[0] = segbase;
3281     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3282
3283     dtv[0] = tls_dtv_generation;
3284     dtv[1] = tls_max_index;
3285
3286     if (oldtls) {
3287         /*
3288          * Copy the static TLS block over whole.
3289          */
3290         oldsegbase = (Elf_Addr) oldtls;
3291         memcpy((void *)(segbase - tls_static_space),
3292                (const void *)(oldsegbase - tls_static_space),
3293                tls_static_space);
3294
3295         /*
3296          * If any dynamic TLS blocks have been created tls_get_addr(),
3297          * move them over.
3298          */
3299         olddtv = ((Elf_Addr**)oldsegbase)[1];
3300         for (i = 0; i < olddtv[1]; i++) {
3301             if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3302                 dtv[i+2] = olddtv[i+2];
3303                 olddtv[i+2] = 0;
3304             }
3305         }
3306
3307         /*
3308          * We assume that this block was the one we created with
3309          * allocate_initial_tls().
3310          */
3311         free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3312     } else {
3313         for (obj = objs; obj; obj = obj->next) {
3314             if (obj->tlsoffset) {
3315                 addr = segbase - obj->tlsoffset;
3316                 memset((void*) (addr + obj->tlsinitsize),
3317                        0, obj->tlssize - obj->tlsinitsize);
3318                 if (obj->tlsinit)
3319                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3320                 dtv[obj->tlsindex + 1] = addr;
3321             }
3322         }
3323     }
3324
3325     return (void*) segbase;
3326 }
3327
3328 void
3329 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3330 {
3331     size_t size;
3332     Elf_Addr* dtv;
3333     int dtvsize, i;
3334     Elf_Addr tlsstart, tlsend;
3335
3336     /*
3337      * Figure out the size of the initial TLS block so that we can
3338      * find stuff which ___tls_get_addr() allocated dynamically.
3339      */
3340     size = round(tls_static_space, tcbalign);
3341
3342     dtv = ((Elf_Addr**)tls)[1];
3343     dtvsize = dtv[1];
3344     tlsend = (Elf_Addr) tls;
3345     tlsstart = tlsend - size;
3346     for (i = 0; i < dtvsize; i++) {
3347         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3348             free((void*) dtv[i+2]);
3349         }
3350     }
3351
3352     free((void*) tlsstart);
3353     free((void*) dtv);
3354 }
3355
3356 #endif
3357
3358 /*
3359  * Allocate TLS block for module with given index.
3360  */
3361 void *
3362 allocate_module_tls(int index)
3363 {
3364     Obj_Entry* obj;
3365     char* p;
3366
3367     for (obj = obj_list; obj; obj = obj->next) {
3368         if (obj->tlsindex == index)
3369             break;
3370     }
3371     if (!obj) {
3372         _rtld_error("Can't find module with TLS index %d", index);
3373         die();
3374     }
3375
3376     p = malloc(obj->tlssize);
3377     if (p == NULL) {
3378         _rtld_error("Cannot allocate TLS block for index %d", index);
3379         die();
3380     }
3381     memcpy(p, obj->tlsinit, obj->tlsinitsize);
3382     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3383
3384     return p;
3385 }
3386
3387 bool
3388 allocate_tls_offset(Obj_Entry *obj)
3389 {
3390     size_t off;
3391
3392     if (obj->tls_done)
3393         return true;
3394
3395     if (obj->tlssize == 0) {
3396         obj->tls_done = true;
3397         return true;
3398     }
3399
3400     if (obj->tlsindex == 1)
3401         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3402     else
3403         off = calculate_tls_offset(tls_last_offset, tls_last_size,
3404                                    obj->tlssize, obj->tlsalign);
3405
3406     /*
3407      * If we have already fixed the size of the static TLS block, we
3408      * must stay within that size. When allocating the static TLS, we
3409      * leave a small amount of space spare to be used for dynamically
3410      * loading modules which use static TLS.
3411      */
3412     if (tls_static_space) {
3413         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3414             return false;
3415     }
3416
3417     tls_last_offset = obj->tlsoffset = off;
3418     tls_last_size = obj->tlssize;
3419     obj->tls_done = true;
3420
3421     return true;
3422 }
3423
3424 void
3425 free_tls_offset(Obj_Entry *obj)
3426 {
3427
3428     /*
3429      * If we were the last thing to allocate out of the static TLS
3430      * block, we give our space back to the 'allocator'. This is a
3431      * simplistic workaround to allow libGL.so.1 to be loaded and
3432      * unloaded multiple times.
3433      */
3434     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3435         == calculate_tls_end(tls_last_offset, tls_last_size)) {
3436         tls_last_offset -= obj->tlssize;
3437         tls_last_size = 0;
3438     }
3439 }
3440
3441 void *
3442 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3443 {
3444     void *ret;
3445     int lockstate;
3446
3447     lockstate = wlock_acquire(rtld_bind_lock);
3448     ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3449     wlock_release(rtld_bind_lock, lockstate);
3450     return (ret);
3451 }
3452
3453 void
3454 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3455 {
3456     int lockstate;
3457
3458     lockstate = wlock_acquire(rtld_bind_lock);
3459     free_tls(tcb, tcbsize, tcbalign);
3460     wlock_release(rtld_bind_lock, lockstate);
3461 }
3462
3463 static void
3464 object_add_name(Obj_Entry *obj, const char *name)
3465 {
3466     Name_Entry *entry;
3467     size_t len;
3468
3469     len = strlen(name);
3470     entry = malloc(sizeof(Name_Entry) + len);
3471
3472     if (entry != NULL) {
3473         strcpy(entry->name, name);
3474         STAILQ_INSERT_TAIL(&obj->names, entry, link);
3475     }
3476 }
3477
3478 static int
3479 object_match_name(const Obj_Entry *obj, const char *name)
3480 {
3481     Name_Entry *entry;
3482
3483     STAILQ_FOREACH(entry, &obj->names, link) {
3484         if (strcmp(name, entry->name) == 0)
3485             return (1);
3486     }
3487     return (0);
3488 }
3489
3490 static Obj_Entry *
3491 locate_dependency(const Obj_Entry *obj, const char *name)
3492 {
3493     const Objlist_Entry *entry;
3494     const Needed_Entry *needed;
3495
3496     STAILQ_FOREACH(entry, &list_main, link) {
3497         if (object_match_name(entry->obj, name))
3498             return entry->obj;
3499     }
3500
3501     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3502         if (needed->obj == NULL)
3503             continue;
3504         if (object_match_name(needed->obj, name))
3505             return needed->obj;
3506     }
3507     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3508         obj->path, name);
3509     die();
3510 }
3511
3512 static int
3513 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3514     const Elf_Vernaux *vna)
3515 {
3516     const Elf_Verdef *vd;
3517     const char *vername;
3518
3519     vername = refobj->strtab + vna->vna_name;
3520     vd = depobj->verdef;
3521     if (vd == NULL) {
3522         _rtld_error("%s: version %s required by %s not defined",
3523             depobj->path, vername, refobj->path);
3524         return (-1);
3525     }
3526     for (;;) {
3527         if (vd->vd_version != VER_DEF_CURRENT) {
3528             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3529                 depobj->path, vd->vd_version);
3530             return (-1);
3531         }
3532         if (vna->vna_hash == vd->vd_hash) {
3533             const Elf_Verdaux *aux = (const Elf_Verdaux *)
3534                 ((char *)vd + vd->vd_aux);
3535             if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3536                 return (0);
3537         }
3538         if (vd->vd_next == 0)
3539             break;
3540         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3541     }
3542     if (vna->vna_flags & VER_FLG_WEAK)
3543         return (0);
3544     _rtld_error("%s: version %s required by %s not found",
3545         depobj->path, vername, refobj->path);
3546     return (-1);
3547 }
3548
3549 static int
3550 rtld_verify_object_versions(Obj_Entry *obj)
3551 {
3552     const Elf_Verneed *vn;
3553     const Elf_Verdef  *vd;
3554     const Elf_Verdaux *vda;
3555     const Elf_Vernaux *vna;
3556     const Obj_Entry *depobj;
3557     int maxvernum, vernum;
3558
3559     maxvernum = 0;
3560     /*
3561      * Walk over defined and required version records and figure out
3562      * max index used by any of them. Do very basic sanity checking
3563      * while there.
3564      */
3565     vn = obj->verneed;
3566     while (vn != NULL) {
3567         if (vn->vn_version != VER_NEED_CURRENT) {
3568             _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3569                 obj->path, vn->vn_version);
3570             return (-1);
3571         }
3572         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3573         for (;;) {
3574             vernum = VER_NEED_IDX(vna->vna_other);
3575             if (vernum > maxvernum)
3576                 maxvernum = vernum;
3577             if (vna->vna_next == 0)
3578                  break;
3579             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3580         }
3581         if (vn->vn_next == 0)
3582             break;
3583         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3584     }
3585
3586     vd = obj->verdef;
3587     while (vd != NULL) {
3588         if (vd->vd_version != VER_DEF_CURRENT) {
3589             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3590                 obj->path, vd->vd_version);
3591             return (-1);
3592         }
3593         vernum = VER_DEF_IDX(vd->vd_ndx);
3594         if (vernum > maxvernum)
3595                 maxvernum = vernum;
3596         if (vd->vd_next == 0)
3597             break;
3598         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3599     }
3600
3601     if (maxvernum == 0)
3602         return (0);
3603
3604     /*
3605      * Store version information in array indexable by version index.
3606      * Verify that object version requirements are satisfied along the
3607      * way.
3608      */
3609     obj->vernum = maxvernum + 1;
3610     obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3611
3612     vd = obj->verdef;
3613     while (vd != NULL) {
3614         if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3615             vernum = VER_DEF_IDX(vd->vd_ndx);
3616             assert(vernum <= maxvernum);
3617             vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3618             obj->vertab[vernum].hash = vd->vd_hash;
3619             obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3620             obj->vertab[vernum].file = NULL;
3621             obj->vertab[vernum].flags = 0;
3622         }
3623         if (vd->vd_next == 0)
3624             break;
3625         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3626     }
3627
3628     vn = obj->verneed;
3629     while (vn != NULL) {
3630         depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3631         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3632         for (;;) {
3633             if (check_object_provided_version(obj, depobj, vna))
3634                 return (-1);
3635             vernum = VER_NEED_IDX(vna->vna_other);
3636             assert(vernum <= maxvernum);
3637             obj->vertab[vernum].hash = vna->vna_hash;
3638             obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3639             obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3640             obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3641                 VER_INFO_HIDDEN : 0;
3642             if (vna->vna_next == 0)
3643                  break;
3644             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3645         }
3646         if (vn->vn_next == 0)
3647             break;
3648         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3649     }
3650     return 0;
3651 }
3652
3653 static int
3654 rtld_verify_versions(const Objlist *objlist)
3655 {
3656     Objlist_Entry *entry;
3657     int rc;
3658
3659     rc = 0;
3660     STAILQ_FOREACH(entry, objlist, link) {
3661         /*
3662          * Skip dummy objects or objects that have their version requirements
3663          * already checked.
3664          */
3665         if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3666             continue;
3667         if (rtld_verify_object_versions(entry->obj) == -1) {
3668             rc = -1;
3669             if (ld_tracing == NULL)
3670                 break;
3671         }
3672     }
3673     if (rc == 0 || ld_tracing != NULL)
3674         rc = rtld_verify_object_versions(&obj_rtld);
3675     return rc;
3676 }
3677
3678 const Ver_Entry *
3679 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3680 {
3681     Elf_Versym vernum;
3682
3683     if (obj->vertab) {
3684         vernum = VER_NDX(obj->versyms[symnum]);
3685         if (vernum >= obj->vernum) {
3686             _rtld_error("%s: symbol %s has wrong verneed value %d",
3687                 obj->path, obj->strtab + symnum, vernum);
3688         } else if (obj->vertab[vernum].hash != 0) {
3689             return &obj->vertab[vernum];
3690         }
3691     }
3692     return NULL;
3693 }
3694
3695 int
3696 __getosreldate(void)
3697 {
3698         size_t len;
3699         int oid[2];
3700         int error, osrel;
3701
3702         if (osreldate != 0)
3703                 return (osreldate);
3704
3705         oid[0] = CTL_KERN;
3706         oid[1] = KERN_OSRELDATE;
3707         osrel = 0;
3708         len = sizeof(osrel);
3709         error = sysctl(oid, 2, &osrel, &len, NULL, 0);
3710         if (error == 0 && osrel > 0 && len == sizeof(osrel))
3711                 osreldate = osrel;
3712         return (osreldate);
3713 }