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