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