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