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