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