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