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