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