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