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