]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/rtld-elf/rtld.c
Update mandoc to 1.14.5
[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_RLD_MAP_REL:
1272                 // The MIPS_RLD_MAP_REL tag stores the offset to the .rld_map
1273                 // section relative to the address of the tag itself.
1274                 *((Elf_Addr *)(__DECONST(char*, dynp) + dynp->d_un.d_val)) =
1275                     (Elf_Addr) &r_debug;
1276                 break;
1277
1278         case DT_MIPS_PLTGOT:
1279                 obj->mips_pltgot = (Elf_Addr *)(obj->relocbase +
1280                     dynp->d_un.d_ptr);
1281                 break;
1282                 
1283 #endif
1284
1285 #ifdef __powerpc64__
1286         case DT_PPC64_GLINK:
1287                 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr);
1288                 break;
1289 #endif
1290
1291         case DT_FLAGS_1:
1292                 if (dynp->d_un.d_val & DF_1_NOOPEN)
1293                     obj->z_noopen = true;
1294                 if (dynp->d_un.d_val & DF_1_ORIGIN)
1295                     obj->z_origin = true;
1296                 if (dynp->d_un.d_val & DF_1_GLOBAL)
1297                     obj->z_global = true;
1298                 if (dynp->d_un.d_val & DF_1_BIND_NOW)
1299                     obj->bind_now = true;
1300                 if (dynp->d_un.d_val & DF_1_NODELETE)
1301                     obj->z_nodelete = true;
1302                 if (dynp->d_un.d_val & DF_1_LOADFLTR)
1303                     obj->z_loadfltr = true;
1304                 if (dynp->d_un.d_val & DF_1_INTERPOSE)
1305                     obj->z_interpose = true;
1306                 if (dynp->d_un.d_val & DF_1_NODEFLIB)
1307                     obj->z_nodeflib = true;
1308             break;
1309
1310         default:
1311             if (!early) {
1312                 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1313                     (long)dynp->d_tag);
1314             }
1315             break;
1316         }
1317     }
1318
1319     obj->traced = false;
1320
1321     if (plttype == DT_RELA) {
1322         obj->pltrela = (const Elf_Rela *) obj->pltrel;
1323         obj->pltrel = NULL;
1324         obj->pltrelasize = obj->pltrelsize;
1325         obj->pltrelsize = 0;
1326     }
1327
1328     /* Determine size of dynsym table (equal to nchains of sysv hash) */
1329     if (obj->valid_hash_sysv)
1330         obj->dynsymcount = obj->nchains;
1331     else if (obj->valid_hash_gnu) {
1332         obj->dynsymcount = 0;
1333         for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) {
1334             if (obj->buckets_gnu[bkt] == 0)
1335                 continue;
1336             hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]];
1337             do
1338                 obj->dynsymcount++;
1339             while ((*hashval++ & 1u) == 0);
1340         }
1341         obj->dynsymcount += obj->symndx_gnu;
1342     }
1343 }
1344
1345 static bool
1346 obj_resolve_origin(Obj_Entry *obj)
1347 {
1348
1349         if (obj->origin_path != NULL)
1350                 return (true);
1351         obj->origin_path = xmalloc(PATH_MAX);
1352         return (rtld_dirname_abs(obj->path, obj->origin_path) != -1);
1353 }
1354
1355 static void
1356 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1357     const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath)
1358 {
1359
1360         if (obj->z_origin && !obj_resolve_origin(obj))
1361                 rtld_die();
1362
1363         if (dyn_runpath != NULL) {
1364                 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val;
1365                 obj->runpath = origin_subst(obj, obj->runpath);
1366         } else if (dyn_rpath != NULL) {
1367                 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val;
1368                 obj->rpath = origin_subst(obj, obj->rpath);
1369         }
1370         if (dyn_soname != NULL)
1371                 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1372 }
1373
1374 static void
1375 digest_dynamic(Obj_Entry *obj, int early)
1376 {
1377         const Elf_Dyn *dyn_rpath;
1378         const Elf_Dyn *dyn_soname;
1379         const Elf_Dyn *dyn_runpath;
1380
1381         digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath);
1382         digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath);
1383 }
1384
1385 /*
1386  * Process a shared object's program header.  This is used only for the
1387  * main program, when the kernel has already loaded the main program
1388  * into memory before calling the dynamic linker.  It creates and
1389  * returns an Obj_Entry structure.
1390  */
1391 static Obj_Entry *
1392 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1393 {
1394     Obj_Entry *obj;
1395     const Elf_Phdr *phlimit = phdr + phnum;
1396     const Elf_Phdr *ph;
1397     Elf_Addr note_start, note_end;
1398     int nsegs = 0;
1399
1400     obj = obj_new();
1401     for (ph = phdr;  ph < phlimit;  ph++) {
1402         if (ph->p_type != PT_PHDR)
1403             continue;
1404
1405         obj->phdr = phdr;
1406         obj->phsize = ph->p_memsz;
1407         obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr;
1408         break;
1409     }
1410
1411     obj->stack_flags = PF_X | PF_R | PF_W;
1412
1413     for (ph = phdr;  ph < phlimit;  ph++) {
1414         switch (ph->p_type) {
1415
1416         case PT_INTERP:
1417             obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1418             break;
1419
1420         case PT_LOAD:
1421             if (nsegs == 0) {   /* First load segment */
1422                 obj->vaddrbase = trunc_page(ph->p_vaddr);
1423                 obj->mapbase = obj->vaddrbase + obj->relocbase;
1424             } else {            /* Last load segment */
1425                 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1426                   obj->vaddrbase;
1427             }
1428             nsegs++;
1429             break;
1430
1431         case PT_DYNAMIC:
1432             obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1433             break;
1434
1435         case PT_TLS:
1436             obj->tlsindex = 1;
1437             obj->tlssize = ph->p_memsz;
1438             obj->tlsalign = ph->p_align;
1439             obj->tlsinitsize = ph->p_filesz;
1440             obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1441             break;
1442
1443         case PT_GNU_STACK:
1444             obj->stack_flags = ph->p_flags;
1445             break;
1446
1447         case PT_GNU_RELRO:
1448             obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1449             obj->relro_size = round_page(ph->p_memsz);
1450             break;
1451
1452         case PT_NOTE:
1453             note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
1454             note_end = note_start + ph->p_filesz;
1455             digest_notes(obj, note_start, note_end);
1456             break;
1457         }
1458     }
1459     if (nsegs < 1) {
1460         _rtld_error("%s: too few PT_LOAD segments", path);
1461         return NULL;
1462     }
1463
1464     obj->entry = entry;
1465     return obj;
1466 }
1467
1468 void
1469 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end)
1470 {
1471         const Elf_Note *note;
1472         const char *note_name;
1473         uintptr_t p;
1474
1475         for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end;
1476             note = (const Elf_Note *)((const char *)(note + 1) +
1477               roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1478               roundup2(note->n_descsz, sizeof(Elf32_Addr)))) {
1479                 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1480                     note->n_descsz != sizeof(int32_t))
1481                         continue;
1482                 if (note->n_type != NT_FREEBSD_ABI_TAG &&
1483                     note->n_type != NT_FREEBSD_FEATURE_CTL &&
1484                     note->n_type != NT_FREEBSD_NOINIT_TAG)
1485                         continue;
1486                 note_name = (const char *)(note + 1);
1487                 if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1488                     sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1489                         continue;
1490                 switch (note->n_type) {
1491                 case NT_FREEBSD_ABI_TAG:
1492                         /* FreeBSD osrel note */
1493                         p = (uintptr_t)(note + 1);
1494                         p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1495                         obj->osrel = *(const int32_t *)(p);
1496                         dbg("note osrel %d", obj->osrel);
1497                         break;
1498                 case NT_FREEBSD_FEATURE_CTL:
1499                         /* FreeBSD ABI feature control note */
1500                         p = (uintptr_t)(note + 1);
1501                         p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1502                         obj->fctl0 = *(const uint32_t *)(p);
1503                         dbg("note fctl0 %#x", obj->fctl0);
1504                         break;
1505                 case NT_FREEBSD_NOINIT_TAG:
1506                         /* FreeBSD 'crt does not call init' note */
1507                         obj->crt_no_init = true;
1508                         dbg("note crt_no_init");
1509                         break;
1510                 }
1511         }
1512 }
1513
1514 static Obj_Entry *
1515 dlcheck(void *handle)
1516 {
1517     Obj_Entry *obj;
1518
1519     TAILQ_FOREACH(obj, &obj_list, next) {
1520         if (obj == (Obj_Entry *) handle)
1521             break;
1522     }
1523
1524     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1525         _rtld_error("Invalid shared object handle %p", handle);
1526         return NULL;
1527     }
1528     return obj;
1529 }
1530
1531 /*
1532  * If the given object is already in the donelist, return true.  Otherwise
1533  * add the object to the list and return false.
1534  */
1535 static bool
1536 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1537 {
1538     unsigned int i;
1539
1540     for (i = 0;  i < dlp->num_used;  i++)
1541         if (dlp->objs[i] == obj)
1542             return true;
1543     /*
1544      * Our donelist allocation should always be sufficient.  But if
1545      * our threads locking isn't working properly, more shared objects
1546      * could have been loaded since we allocated the list.  That should
1547      * never happen, but we'll handle it properly just in case it does.
1548      */
1549     if (dlp->num_used < dlp->num_alloc)
1550         dlp->objs[dlp->num_used++] = obj;
1551     return false;
1552 }
1553
1554 /*
1555  * Hash function for symbol table lookup.  Don't even think about changing
1556  * this.  It is specified by the System V ABI.
1557  */
1558 unsigned long
1559 elf_hash(const char *name)
1560 {
1561     const unsigned char *p = (const unsigned char *) name;
1562     unsigned long h = 0;
1563     unsigned long g;
1564
1565     while (*p != '\0') {
1566         h = (h << 4) + *p++;
1567         if ((g = h & 0xf0000000) != 0)
1568             h ^= g >> 24;
1569         h &= ~g;
1570     }
1571     return h;
1572 }
1573
1574 /*
1575  * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1576  * unsigned in case it's implemented with a wider type.
1577  */
1578 static uint32_t
1579 gnu_hash(const char *s)
1580 {
1581         uint32_t h;
1582         unsigned char c;
1583
1584         h = 5381;
1585         for (c = *s; c != '\0'; c = *++s)
1586                 h = h * 33 + c;
1587         return (h & 0xffffffff);
1588 }
1589
1590
1591 /*
1592  * Find the library with the given name, and return its full pathname.
1593  * The returned string is dynamically allocated.  Generates an error
1594  * message and returns NULL if the library cannot be found.
1595  *
1596  * If the second argument is non-NULL, then it refers to an already-
1597  * loaded shared object, whose library search path will be searched.
1598  *
1599  * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1600  * descriptor (which is close-on-exec) will be passed out via the third
1601  * argument.
1602  *
1603  * The search order is:
1604  *   DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1605  *   DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1606  *   LD_LIBRARY_PATH
1607  *   DT_RUNPATH in the referencing file
1608  *   ldconfig hints (if -z nodefaultlib, filter out default library directories
1609  *       from list)
1610  *   /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1611  *
1612  * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1613  */
1614 static char *
1615 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1616 {
1617         char *pathname, *refobj_path;
1618         const char *name;
1619         bool nodeflib, objgiven;
1620
1621         objgiven = refobj != NULL;
1622
1623         if (libmap_disable || !objgiven ||
1624             (name = lm_find(refobj->path, xname)) == NULL)
1625                 name = xname;
1626
1627         if (strchr(name, '/') != NULL) {        /* Hard coded pathname */
1628                 if (name[0] != '/' && !trust) {
1629                         _rtld_error("Absolute pathname required "
1630                             "for shared object \"%s\"", name);
1631                         return (NULL);
1632                 }
1633                 return (origin_subst(__DECONST(Obj_Entry *, refobj),
1634                     __DECONST(char *, name)));
1635         }
1636
1637         dbg(" Searching for \"%s\"", name);
1638         refobj_path = objgiven ? refobj->path : NULL;
1639
1640         /*
1641          * If refobj->rpath != NULL, then refobj->runpath is NULL.  Fall
1642          * back to pre-conforming behaviour if user requested so with
1643          * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1644          * nodeflib.
1645          */
1646         if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1647                 pathname = search_library_path(name, ld_library_path,
1648                     refobj_path, fdp);
1649                 if (pathname != NULL)
1650                         return (pathname);
1651                 if (refobj != NULL) {
1652                         pathname = search_library_path(name, refobj->rpath,
1653                             refobj_path, fdp);
1654                         if (pathname != NULL)
1655                                 return (pathname);
1656                 }
1657                 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1658                 if (pathname != NULL)
1659                         return (pathname);
1660                 pathname = search_library_path(name, gethints(false),
1661                     refobj_path, fdp);
1662                 if (pathname != NULL)
1663                         return (pathname);
1664                 pathname = search_library_path(name, ld_standard_library_path,
1665                     refobj_path, fdp);
1666                 if (pathname != NULL)
1667                         return (pathname);
1668         } else {
1669                 nodeflib = objgiven ? refobj->z_nodeflib : false;
1670                 if (objgiven) {
1671                         pathname = search_library_path(name, refobj->rpath,
1672                             refobj->path, fdp);
1673                         if (pathname != NULL)
1674                                 return (pathname);
1675                 }
1676                 if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1677                         pathname = search_library_path(name, obj_main->rpath,
1678                             refobj_path, fdp);
1679                         if (pathname != NULL)
1680                                 return (pathname);
1681                 }
1682                 pathname = search_library_path(name, ld_library_path,
1683                     refobj_path, fdp);
1684                 if (pathname != NULL)
1685                         return (pathname);
1686                 if (objgiven) {
1687                         pathname = search_library_path(name, refobj->runpath,
1688                             refobj_path, fdp);
1689                         if (pathname != NULL)
1690                                 return (pathname);
1691                 }
1692                 pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1693                 if (pathname != NULL)
1694                         return (pathname);
1695                 pathname = search_library_path(name, gethints(nodeflib),
1696                     refobj_path, fdp);
1697                 if (pathname != NULL)
1698                         return (pathname);
1699                 if (objgiven && !nodeflib) {
1700                         pathname = search_library_path(name,
1701                             ld_standard_library_path, refobj_path, fdp);
1702                         if (pathname != NULL)
1703                                 return (pathname);
1704                 }
1705         }
1706
1707         if (objgiven && refobj->path != NULL) {
1708                 _rtld_error("Shared object \"%s\" not found, "
1709                     "required by \"%s\"", name, basename(refobj->path));
1710         } else {
1711                 _rtld_error("Shared object \"%s\" not found", name);
1712         }
1713         return (NULL);
1714 }
1715
1716 /*
1717  * Given a symbol number in a referencing object, find the corresponding
1718  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1719  * no definition was found.  Returns a pointer to the Obj_Entry of the
1720  * defining object via the reference parameter DEFOBJ_OUT.
1721  */
1722 const Elf_Sym *
1723 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1724     const Obj_Entry **defobj_out, int flags, SymCache *cache,
1725     RtldLockState *lockstate)
1726 {
1727     const Elf_Sym *ref;
1728     const Elf_Sym *def;
1729     const Obj_Entry *defobj;
1730     const Ver_Entry *ve;
1731     SymLook req;
1732     const char *name;
1733     int res;
1734
1735     /*
1736      * If we have already found this symbol, get the information from
1737      * the cache.
1738      */
1739     if (symnum >= refobj->dynsymcount)
1740         return NULL;    /* Bad object */
1741     if (cache != NULL && cache[symnum].sym != NULL) {
1742         *defobj_out = cache[symnum].obj;
1743         return cache[symnum].sym;
1744     }
1745
1746     ref = refobj->symtab + symnum;
1747     name = refobj->strtab + ref->st_name;
1748     def = NULL;
1749     defobj = NULL;
1750     ve = NULL;
1751
1752     /*
1753      * We don't have to do a full scale lookup if the symbol is local.
1754      * We know it will bind to the instance in this load module; to
1755      * which we already have a pointer (ie ref). By not doing a lookup,
1756      * we not only improve performance, but it also avoids unresolvable
1757      * symbols when local symbols are not in the hash table. This has
1758      * been seen with the ia64 toolchain.
1759      */
1760     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1761         if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1762             _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1763                 symnum);
1764         }
1765         symlook_init(&req, name);
1766         req.flags = flags;
1767         ve = req.ventry = fetch_ventry(refobj, symnum);
1768         req.lockstate = lockstate;
1769         res = symlook_default(&req, refobj);
1770         if (res == 0) {
1771             def = req.sym_out;
1772             defobj = req.defobj_out;
1773         }
1774     } else {
1775         def = ref;
1776         defobj = refobj;
1777     }
1778
1779     /*
1780      * If we found no definition and the reference is weak, treat the
1781      * symbol as having the value zero.
1782      */
1783     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1784         def = &sym_zero;
1785         defobj = obj_main;
1786     }
1787
1788     if (def != NULL) {
1789         *defobj_out = defobj;
1790         /* Record the information in the cache to avoid subsequent lookups. */
1791         if (cache != NULL) {
1792             cache[symnum].sym = def;
1793             cache[symnum].obj = defobj;
1794         }
1795     } else {
1796         if (refobj != &obj_rtld)
1797             _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
1798               ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
1799     }
1800     return def;
1801 }
1802
1803 /*
1804  * Return the search path from the ldconfig hints file, reading it if
1805  * necessary.  If nostdlib is true, then the default search paths are
1806  * not added to result.
1807  *
1808  * Returns NULL if there are problems with the hints file,
1809  * or if the search path there is empty.
1810  */
1811 static const char *
1812 gethints(bool nostdlib)
1813 {
1814         static char *filtered_path;
1815         static const char *hints;
1816         static struct elfhints_hdr hdr;
1817         struct fill_search_info_args sargs, hargs;
1818         struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
1819         struct dl_serpath *SLPpath, *hintpath;
1820         char *p;
1821         struct stat hint_stat;
1822         unsigned int SLPndx, hintndx, fndx, fcount;
1823         int fd;
1824         size_t flen;
1825         uint32_t dl;
1826         bool skip;
1827
1828         /* First call, read the hints file */
1829         if (hints == NULL) {
1830                 /* Keep from trying again in case the hints file is bad. */
1831                 hints = "";
1832
1833                 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1)
1834                         return (NULL);
1835
1836                 /*
1837                  * Check of hdr.dirlistlen value against type limit
1838                  * intends to pacify static analyzers.  Further
1839                  * paranoia leads to checks that dirlist is fully
1840                  * contained in the file range.
1841                  */
1842                 if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1843                     hdr.magic != ELFHINTS_MAGIC ||
1844                     hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 ||
1845                     fstat(fd, &hint_stat) == -1) {
1846 cleanup1:
1847                         close(fd);
1848                         hdr.dirlistlen = 0;
1849                         return (NULL);
1850                 }
1851                 dl = hdr.strtab;
1852                 if (dl + hdr.dirlist < dl)
1853                         goto cleanup1;
1854                 dl += hdr.dirlist;
1855                 if (dl + hdr.dirlistlen < dl)
1856                         goto cleanup1;
1857                 dl += hdr.dirlistlen;
1858                 if (dl > hint_stat.st_size)
1859                         goto cleanup1;
1860                 p = xmalloc(hdr.dirlistlen + 1);
1861                 if (pread(fd, p, hdr.dirlistlen + 1,
1862                     hdr.strtab + hdr.dirlist) != (ssize_t)hdr.dirlistlen + 1 ||
1863                     p[hdr.dirlistlen] != '\0') {
1864                         free(p);
1865                         goto cleanup1;
1866                 }
1867                 hints = p;
1868                 close(fd);
1869         }
1870
1871         /*
1872          * If caller agreed to receive list which includes the default
1873          * paths, we are done. Otherwise, if we still did not
1874          * calculated filtered result, do it now.
1875          */
1876         if (!nostdlib)
1877                 return (hints[0] != '\0' ? hints : NULL);
1878         if (filtered_path != NULL)
1879                 goto filt_ret;
1880
1881         /*
1882          * Obtain the list of all configured search paths, and the
1883          * list of the default paths.
1884          *
1885          * First estimate the size of the results.
1886          */
1887         smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1888         smeta.dls_cnt = 0;
1889         hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
1890         hmeta.dls_cnt = 0;
1891
1892         sargs.request = RTLD_DI_SERINFOSIZE;
1893         sargs.serinfo = &smeta;
1894         hargs.request = RTLD_DI_SERINFOSIZE;
1895         hargs.serinfo = &hmeta;
1896
1897         path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1898             &sargs);
1899         path_enumerate(hints, fill_search_info, NULL, &hargs);
1900
1901         SLPinfo = xmalloc(smeta.dls_size);
1902         hintinfo = xmalloc(hmeta.dls_size);
1903
1904         /*
1905          * Next fetch both sets of paths.
1906          */
1907         sargs.request = RTLD_DI_SERINFO;
1908         sargs.serinfo = SLPinfo;
1909         sargs.serpath = &SLPinfo->dls_serpath[0];
1910         sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
1911
1912         hargs.request = RTLD_DI_SERINFO;
1913         hargs.serinfo = hintinfo;
1914         hargs.serpath = &hintinfo->dls_serpath[0];
1915         hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
1916
1917         path_enumerate(ld_standard_library_path, fill_search_info, NULL,
1918             &sargs);
1919         path_enumerate(hints, fill_search_info, NULL, &hargs);
1920
1921         /*
1922          * Now calculate the difference between two sets, by excluding
1923          * standard paths from the full set.
1924          */
1925         fndx = 0;
1926         fcount = 0;
1927         filtered_path = xmalloc(hdr.dirlistlen + 1);
1928         hintpath = &hintinfo->dls_serpath[0];
1929         for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
1930                 skip = false;
1931                 SLPpath = &SLPinfo->dls_serpath[0];
1932                 /*
1933                  * Check each standard path against current.
1934                  */
1935                 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
1936                         /* matched, skip the path */
1937                         if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
1938                                 skip = true;
1939                                 break;
1940                         }
1941                 }
1942                 if (skip)
1943                         continue;
1944                 /*
1945                  * Not matched against any standard path, add the path
1946                  * to result. Separate consequtive paths with ':'.
1947                  */
1948                 if (fcount > 0) {
1949                         filtered_path[fndx] = ':';
1950                         fndx++;
1951                 }
1952                 fcount++;
1953                 flen = strlen(hintpath->dls_name);
1954                 strncpy((filtered_path + fndx), hintpath->dls_name, flen);
1955                 fndx += flen;
1956         }
1957         filtered_path[fndx] = '\0';
1958
1959         free(SLPinfo);
1960         free(hintinfo);
1961
1962 filt_ret:
1963         return (filtered_path[0] != '\0' ? filtered_path : NULL);
1964 }
1965
1966 static void
1967 init_dag(Obj_Entry *root)
1968 {
1969     const Needed_Entry *needed;
1970     const Objlist_Entry *elm;
1971     DoneList donelist;
1972
1973     if (root->dag_inited)
1974         return;
1975     donelist_init(&donelist);
1976
1977     /* Root object belongs to own DAG. */
1978     objlist_push_tail(&root->dldags, root);
1979     objlist_push_tail(&root->dagmembers, root);
1980     donelist_check(&donelist, root);
1981
1982     /*
1983      * Add dependencies of root object to DAG in breadth order
1984      * by exploiting the fact that each new object get added
1985      * to the tail of the dagmembers list.
1986      */
1987     STAILQ_FOREACH(elm, &root->dagmembers, link) {
1988         for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1989             if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1990                 continue;
1991             objlist_push_tail(&needed->obj->dldags, root);
1992             objlist_push_tail(&root->dagmembers, needed->obj);
1993         }
1994     }
1995     root->dag_inited = true;
1996 }
1997
1998 static void
1999 init_marker(Obj_Entry *marker)
2000 {
2001
2002         bzero(marker, sizeof(*marker));
2003         marker->marker = true;
2004 }
2005
2006 Obj_Entry *
2007 globallist_curr(const Obj_Entry *obj)
2008 {
2009
2010         for (;;) {
2011                 if (obj == NULL)
2012                         return (NULL);
2013                 if (!obj->marker)
2014                         return (__DECONST(Obj_Entry *, obj));
2015                 obj = TAILQ_PREV(obj, obj_entry_q, next);
2016         }
2017 }
2018
2019 Obj_Entry *
2020 globallist_next(const Obj_Entry *obj)
2021 {
2022
2023         for (;;) {
2024                 obj = TAILQ_NEXT(obj, next);
2025                 if (obj == NULL)
2026                         return (NULL);
2027                 if (!obj->marker)
2028                         return (__DECONST(Obj_Entry *, obj));
2029         }
2030 }
2031
2032 /* Prevent the object from being unmapped while the bind lock is dropped. */
2033 static void
2034 hold_object(Obj_Entry *obj)
2035 {
2036
2037         obj->holdcount++;
2038 }
2039
2040 static void
2041 unhold_object(Obj_Entry *obj)
2042 {
2043
2044         assert(obj->holdcount > 0);
2045         if (--obj->holdcount == 0 && obj->unholdfree)
2046                 release_object(obj);
2047 }
2048
2049 static void
2050 process_z(Obj_Entry *root)
2051 {
2052         const Objlist_Entry *elm;
2053         Obj_Entry *obj;
2054
2055         /*
2056          * Walk over object DAG and process every dependent object
2057          * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2058          * to grow their own DAG.
2059          *
2060          * For DF_1_GLOBAL, DAG is required for symbol lookups in
2061          * symlook_global() to work.
2062          *
2063          * For DF_1_NODELETE, the DAG should have its reference upped.
2064          */
2065         STAILQ_FOREACH(elm, &root->dagmembers, link) {
2066                 obj = elm->obj;
2067                 if (obj == NULL)
2068                         continue;
2069                 if (obj->z_nodelete && !obj->ref_nodel) {
2070                         dbg("obj %s -z nodelete", obj->path);
2071                         init_dag(obj);
2072                         ref_dag(obj);
2073                         obj->ref_nodel = true;
2074                 }
2075                 if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2076                         dbg("obj %s -z global", obj->path);
2077                         objlist_push_tail(&list_global, obj);
2078                         init_dag(obj);
2079                 }
2080         }
2081 }
2082 /*
2083  * Initialize the dynamic linker.  The argument is the address at which
2084  * the dynamic linker has been mapped into memory.  The primary task of
2085  * this function is to relocate the dynamic linker.
2086  */
2087 static void
2088 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2089 {
2090     Obj_Entry objtmp;   /* Temporary rtld object */
2091     const Elf_Ehdr *ehdr;
2092     const Elf_Dyn *dyn_rpath;
2093     const Elf_Dyn *dyn_soname;
2094     const Elf_Dyn *dyn_runpath;
2095
2096 #ifdef RTLD_INIT_PAGESIZES_EARLY
2097     /* The page size is required by the dynamic memory allocator. */
2098     init_pagesizes(aux_info);
2099 #endif
2100
2101     /*
2102      * Conjure up an Obj_Entry structure for the dynamic linker.
2103      *
2104      * The "path" member can't be initialized yet because string constants
2105      * cannot yet be accessed. Below we will set it correctly.
2106      */
2107     memset(&objtmp, 0, sizeof(objtmp));
2108     objtmp.path = NULL;
2109     objtmp.rtld = true;
2110     objtmp.mapbase = mapbase;
2111 #ifdef PIC
2112     objtmp.relocbase = mapbase;
2113 #endif
2114
2115     objtmp.dynamic = rtld_dynamic(&objtmp);
2116     digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2117     assert(objtmp.needed == NULL);
2118 #if !defined(__mips__)
2119     /* MIPS has a bogus DT_TEXTREL. */
2120     assert(!objtmp.textrel);
2121 #endif
2122     /*
2123      * Temporarily put the dynamic linker entry into the object list, so
2124      * that symbols can be found.
2125      */
2126     relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2127
2128     ehdr = (Elf_Ehdr *)mapbase;
2129     objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2130     objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2131
2132     /* Initialize the object list. */
2133     TAILQ_INIT(&obj_list);
2134
2135     /* Now that non-local variables can be accesses, copy out obj_rtld. */
2136     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2137
2138 #ifndef RTLD_INIT_PAGESIZES_EARLY
2139     /* The page size is required by the dynamic memory allocator. */
2140     init_pagesizes(aux_info);
2141 #endif
2142
2143     if (aux_info[AT_OSRELDATE] != NULL)
2144             osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2145
2146     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2147
2148     /* Replace the path with a dynamically allocated copy. */
2149     obj_rtld.path = xstrdup(ld_path_rtld);
2150
2151     r_debug.r_brk = r_debug_state;
2152     r_debug.r_state = RT_CONSISTENT;
2153 }
2154
2155 /*
2156  * Retrieve the array of supported page sizes.  The kernel provides the page
2157  * sizes in increasing order.
2158  */
2159 static void
2160 init_pagesizes(Elf_Auxinfo **aux_info)
2161 {
2162         static size_t psa[MAXPAGESIZES];
2163         int mib[2];
2164         size_t len, size;
2165
2166         if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2167             NULL) {
2168                 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2169                 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2170         } else {
2171                 len = 2;
2172                 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2173                         size = sizeof(psa);
2174                 else {
2175                         /* As a fallback, retrieve the base page size. */
2176                         size = sizeof(psa[0]);
2177                         if (aux_info[AT_PAGESZ] != NULL) {
2178                                 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2179                                 goto psa_filled;
2180                         } else {
2181                                 mib[0] = CTL_HW;
2182                                 mib[1] = HW_PAGESIZE;
2183                                 len = 2;
2184                         }
2185                 }
2186                 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2187                         _rtld_error("sysctl for hw.pagesize(s) failed");
2188                         rtld_die();
2189                 }
2190 psa_filled:
2191                 pagesizes = psa;
2192         }
2193         npagesizes = size / sizeof(pagesizes[0]);
2194         /* Discard any invalid entries at the end of the array. */
2195         while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2196                 npagesizes--;
2197 }
2198
2199 /*
2200  * Add the init functions from a needed object list (and its recursive
2201  * needed objects) to "list".  This is not used directly; it is a helper
2202  * function for initlist_add_objects().  The write lock must be held
2203  * when this function is called.
2204  */
2205 static void
2206 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2207 {
2208     /* Recursively process the successor needed objects. */
2209     if (needed->next != NULL)
2210         initlist_add_neededs(needed->next, list);
2211
2212     /* Process the current needed object. */
2213     if (needed->obj != NULL)
2214         initlist_add_objects(needed->obj, needed->obj, list);
2215 }
2216
2217 /*
2218  * Scan all of the DAGs rooted in the range of objects from "obj" to
2219  * "tail" and add their init functions to "list".  This recurses over
2220  * the DAGs and ensure the proper init ordering such that each object's
2221  * needed libraries are initialized before the object itself.  At the
2222  * same time, this function adds the objects to the global finalization
2223  * list "list_fini" in the opposite order.  The write lock must be
2224  * held when this function is called.
2225  */
2226 static void
2227 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2228 {
2229     Obj_Entry *nobj;
2230
2231     if (obj->init_scanned || obj->init_done)
2232         return;
2233     obj->init_scanned = true;
2234
2235     /* Recursively process the successor objects. */
2236     nobj = globallist_next(obj);
2237     if (nobj != NULL && obj != tail)
2238         initlist_add_objects(nobj, tail, list);
2239
2240     /* Recursively process the needed objects. */
2241     if (obj->needed != NULL)
2242         initlist_add_neededs(obj->needed, list);
2243     if (obj->needed_filtees != NULL)
2244         initlist_add_neededs(obj->needed_filtees, list);
2245     if (obj->needed_aux_filtees != NULL)
2246         initlist_add_neededs(obj->needed_aux_filtees, list);
2247
2248     /* Add the object to the init list. */
2249     objlist_push_tail(list, obj);
2250
2251     /* Add the object to the global fini list in the reverse order. */
2252     if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2253       && !obj->on_fini_list) {
2254         objlist_push_head(&list_fini, obj);
2255         obj->on_fini_list = true;
2256     }
2257 }
2258
2259 #ifndef FPTR_TARGET
2260 #define FPTR_TARGET(f)  ((Elf_Addr) (f))
2261 #endif
2262
2263 static void
2264 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2265 {
2266     Needed_Entry *needed, *needed1;
2267
2268     for (needed = n; needed != NULL; needed = needed->next) {
2269         if (needed->obj != NULL) {
2270             dlclose_locked(needed->obj, lockstate);
2271             needed->obj = NULL;
2272         }
2273     }
2274     for (needed = n; needed != NULL; needed = needed1) {
2275         needed1 = needed->next;
2276         free(needed);
2277     }
2278 }
2279
2280 static void
2281 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2282 {
2283
2284         free_needed_filtees(obj->needed_filtees, lockstate);
2285         obj->needed_filtees = NULL;
2286         free_needed_filtees(obj->needed_aux_filtees, lockstate);
2287         obj->needed_aux_filtees = NULL;
2288         obj->filtees_loaded = false;
2289 }
2290
2291 static void
2292 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2293     RtldLockState *lockstate)
2294 {
2295
2296     for (; needed != NULL; needed = needed->next) {
2297         needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2298           flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2299           RTLD_LOCAL, lockstate);
2300     }
2301 }
2302
2303 static void
2304 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2305 {
2306
2307     lock_restart_for_upgrade(lockstate);
2308     if (!obj->filtees_loaded) {
2309         load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2310         load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2311         obj->filtees_loaded = true;
2312     }
2313 }
2314
2315 static int
2316 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2317 {
2318     Obj_Entry *obj1;
2319
2320     for (; needed != NULL; needed = needed->next) {
2321         obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2322           flags & ~RTLD_LO_NOLOAD);
2323         if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2324             return (-1);
2325     }
2326     return (0);
2327 }
2328
2329 /*
2330  * Given a shared object, traverse its list of needed objects, and load
2331  * each of them.  Returns 0 on success.  Generates an error message and
2332  * returns -1 on failure.
2333  */
2334 static int
2335 load_needed_objects(Obj_Entry *first, int flags)
2336 {
2337     Obj_Entry *obj;
2338
2339     for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2340         if (obj->marker)
2341             continue;
2342         if (process_needed(obj, obj->needed, flags) == -1)
2343             return (-1);
2344     }
2345     return (0);
2346 }
2347
2348 static int
2349 load_preload_objects(void)
2350 {
2351     char *p = ld_preload;
2352     Obj_Entry *obj;
2353     static const char delim[] = " \t:;";
2354
2355     if (p == NULL)
2356         return 0;
2357
2358     p += strspn(p, delim);
2359     while (*p != '\0') {
2360         size_t len = strcspn(p, delim);
2361         char savech;
2362
2363         savech = p[len];
2364         p[len] = '\0';
2365         obj = load_object(p, -1, NULL, 0);
2366         if (obj == NULL)
2367             return -1;  /* XXX - cleanup */
2368         obj->z_interpose = true;
2369         p[len] = savech;
2370         p += len;
2371         p += strspn(p, delim);
2372     }
2373     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2374     return 0;
2375 }
2376
2377 static const char *
2378 printable_path(const char *path)
2379 {
2380
2381         return (path == NULL ? "<unknown>" : path);
2382 }
2383
2384 /*
2385  * Load a shared object into memory, if it is not already loaded.  The
2386  * object may be specified by name or by user-supplied file descriptor
2387  * fd_u. In the later case, the fd_u descriptor is not closed, but its
2388  * duplicate is.
2389  *
2390  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
2391  * on failure.
2392  */
2393 static Obj_Entry *
2394 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2395 {
2396     Obj_Entry *obj;
2397     int fd;
2398     struct stat sb;
2399     char *path;
2400
2401     fd = -1;
2402     if (name != NULL) {
2403         TAILQ_FOREACH(obj, &obj_list, next) {
2404             if (obj->marker || obj->doomed)
2405                 continue;
2406             if (object_match_name(obj, name))
2407                 return (obj);
2408         }
2409
2410         path = find_library(name, refobj, &fd);
2411         if (path == NULL)
2412             return (NULL);
2413     } else
2414         path = NULL;
2415
2416     if (fd >= 0) {
2417         /*
2418          * search_library_pathfds() opens a fresh file descriptor for the
2419          * library, so there is no need to dup().
2420          */
2421     } else if (fd_u == -1) {
2422         /*
2423          * If we didn't find a match by pathname, or the name is not
2424          * supplied, open the file and check again by device and inode.
2425          * This avoids false mismatches caused by multiple links or ".."
2426          * in pathnames.
2427          *
2428          * To avoid a race, we open the file and use fstat() rather than
2429          * using stat().
2430          */
2431         if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2432             _rtld_error("Cannot open \"%s\"", path);
2433             free(path);
2434             return (NULL);
2435         }
2436     } else {
2437         fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2438         if (fd == -1) {
2439             _rtld_error("Cannot dup fd");
2440             free(path);
2441             return (NULL);
2442         }
2443     }
2444     if (fstat(fd, &sb) == -1) {
2445         _rtld_error("Cannot fstat \"%s\"", printable_path(path));
2446         close(fd);
2447         free(path);
2448         return NULL;
2449     }
2450     TAILQ_FOREACH(obj, &obj_list, next) {
2451         if (obj->marker || obj->doomed)
2452             continue;
2453         if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2454             break;
2455     }
2456     if (obj != NULL && name != NULL) {
2457         object_add_name(obj, name);
2458         free(path);
2459         close(fd);
2460         return obj;
2461     }
2462     if (flags & RTLD_LO_NOLOAD) {
2463         free(path);
2464         close(fd);
2465         return (NULL);
2466     }
2467
2468     /* First use of this object, so we must map it in */
2469     obj = do_load_object(fd, name, path, &sb, flags);
2470     if (obj == NULL)
2471         free(path);
2472     close(fd);
2473
2474     return obj;
2475 }
2476
2477 static Obj_Entry *
2478 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2479   int flags)
2480 {
2481     Obj_Entry *obj;
2482     struct statfs fs;
2483
2484     /*
2485      * but first, make sure that environment variables haven't been
2486      * used to circumvent the noexec flag on a filesystem.
2487      */
2488     if (dangerous_ld_env) {
2489         if (fstatfs(fd, &fs) != 0) {
2490             _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
2491             return NULL;
2492         }
2493         if (fs.f_flags & MNT_NOEXEC) {
2494             _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2495             return NULL;
2496         }
2497     }
2498     dbg("loading \"%s\"", printable_path(path));
2499     obj = map_object(fd, printable_path(path), sbp);
2500     if (obj == NULL)
2501         return NULL;
2502
2503     /*
2504      * If DT_SONAME is present in the object, digest_dynamic2 already
2505      * added it to the object names.
2506      */
2507     if (name != NULL)
2508         object_add_name(obj, name);
2509     obj->path = path;
2510     digest_dynamic(obj, 0);
2511     dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2512         obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2513     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2514       RTLD_LO_DLOPEN) {
2515         dbg("refusing to load non-loadable \"%s\"", obj->path);
2516         _rtld_error("Cannot dlopen non-loadable %s", obj->path);
2517         munmap(obj->mapbase, obj->mapsize);
2518         obj_free(obj);
2519         return (NULL);
2520     }
2521
2522     obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2523     TAILQ_INSERT_TAIL(&obj_list, obj, next);
2524     obj_count++;
2525     obj_loads++;
2526     linkmap_add(obj);   /* for GDB & dlinfo() */
2527     max_stack_flags |= obj->stack_flags;
2528
2529     dbg("  %p .. %p: %s", obj->mapbase,
2530          obj->mapbase + obj->mapsize - 1, obj->path);
2531     if (obj->textrel)
2532         dbg("  WARNING: %s has impure text", obj->path);
2533     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2534         obj->path);    
2535
2536     return obj;
2537 }
2538
2539 static Obj_Entry *
2540 obj_from_addr(const void *addr)
2541 {
2542     Obj_Entry *obj;
2543
2544     TAILQ_FOREACH(obj, &obj_list, next) {
2545         if (obj->marker)
2546             continue;
2547         if (addr < (void *) obj->mapbase)
2548             continue;
2549         if (addr < (void *)(obj->mapbase + obj->mapsize))
2550             return obj;
2551     }
2552     return NULL;
2553 }
2554
2555 static void
2556 preinit_main(void)
2557 {
2558     Elf_Addr *preinit_addr;
2559     int index;
2560
2561     preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2562     if (preinit_addr == NULL)
2563         return;
2564
2565     for (index = 0; index < obj_main->preinit_array_num; index++) {
2566         if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2567             dbg("calling preinit function for %s at %p", obj_main->path,
2568               (void *)preinit_addr[index]);
2569             LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2570               0, 0, obj_main->path);
2571             call_init_pointer(obj_main, preinit_addr[index]);
2572         }
2573     }
2574 }
2575
2576 /*
2577  * Call the finalization functions for each of the objects in "list"
2578  * belonging to the DAG of "root" and referenced once. If NULL "root"
2579  * is specified, every finalization function will be called regardless
2580  * of the reference count and the list elements won't be freed. All of
2581  * the objects are expected to have non-NULL fini functions.
2582  */
2583 static void
2584 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2585 {
2586     Objlist_Entry *elm;
2587     char *saved_msg;
2588     Elf_Addr *fini_addr;
2589     int index;
2590
2591     assert(root == NULL || root->refcount == 1);
2592
2593     if (root != NULL)
2594         root->doomed = true;
2595
2596     /*
2597      * Preserve the current error message since a fini function might
2598      * call into the dynamic linker and overwrite it.
2599      */
2600     saved_msg = errmsg_save();
2601     do {
2602         STAILQ_FOREACH(elm, list, link) {
2603             if (root != NULL && (elm->obj->refcount != 1 ||
2604               objlist_find(&root->dagmembers, elm->obj) == NULL))
2605                 continue;
2606             /* Remove object from fini list to prevent recursive invocation. */
2607             STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2608             /* Ensure that new references cannot be acquired. */
2609             elm->obj->doomed = true;
2610
2611             hold_object(elm->obj);
2612             lock_release(rtld_bind_lock, lockstate);
2613             /*
2614              * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2615              * When this happens, DT_FINI_ARRAY is processed first.
2616              */
2617             fini_addr = (Elf_Addr *)elm->obj->fini_array;
2618             if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2619                 for (index = elm->obj->fini_array_num - 1; index >= 0;
2620                   index--) {
2621                     if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2622                         dbg("calling fini function for %s at %p",
2623                             elm->obj->path, (void *)fini_addr[index]);
2624                         LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2625                             (void *)fini_addr[index], 0, 0, elm->obj->path);
2626                         call_initfini_pointer(elm->obj, fini_addr[index]);
2627                     }
2628                 }
2629             }
2630             if (elm->obj->fini != (Elf_Addr)NULL) {
2631                 dbg("calling fini function for %s at %p", elm->obj->path,
2632                     (void *)elm->obj->fini);
2633                 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2634                     0, 0, elm->obj->path);
2635                 call_initfini_pointer(elm->obj, elm->obj->fini);
2636             }
2637             wlock_acquire(rtld_bind_lock, lockstate);
2638             unhold_object(elm->obj);
2639             /* No need to free anything if process is going down. */
2640             if (root != NULL)
2641                 free(elm);
2642             /*
2643              * We must restart the list traversal after every fini call
2644              * because a dlclose() call from the fini function or from
2645              * another thread might have modified the reference counts.
2646              */
2647             break;
2648         }
2649     } while (elm != NULL);
2650     errmsg_restore(saved_msg);
2651 }
2652
2653 /*
2654  * Call the initialization functions for each of the objects in
2655  * "list".  All of the objects are expected to have non-NULL init
2656  * functions.
2657  */
2658 static void
2659 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2660 {
2661     Objlist_Entry *elm;
2662     Obj_Entry *obj;
2663     char *saved_msg;
2664     Elf_Addr *init_addr;
2665     int index;
2666
2667     /*
2668      * Clean init_scanned flag so that objects can be rechecked and
2669      * possibly initialized earlier if any of vectors called below
2670      * cause the change by using dlopen.
2671      */
2672     TAILQ_FOREACH(obj, &obj_list, next) {
2673         if (obj->marker)
2674             continue;
2675         obj->init_scanned = false;
2676     }
2677
2678     /*
2679      * Preserve the current error message since an init function might
2680      * call into the dynamic linker and overwrite it.
2681      */
2682     saved_msg = errmsg_save();
2683     STAILQ_FOREACH(elm, list, link) {
2684         if (elm->obj->init_done) /* Initialized early. */
2685             continue;
2686         /*
2687          * Race: other thread might try to use this object before current
2688          * one completes the initialization. Not much can be done here
2689          * without better locking.
2690          */
2691         elm->obj->init_done = true;
2692         hold_object(elm->obj);
2693         lock_release(rtld_bind_lock, lockstate);
2694
2695         /*
2696          * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2697          * When this happens, DT_INIT is processed first.
2698          */
2699         if (elm->obj->init != (Elf_Addr)NULL) {
2700             dbg("calling init function for %s at %p", elm->obj->path,
2701                 (void *)elm->obj->init);
2702             LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2703                 0, 0, elm->obj->path);
2704             call_initfini_pointer(elm->obj, elm->obj->init);
2705         }
2706         init_addr = (Elf_Addr *)elm->obj->init_array;
2707         if (init_addr != NULL) {
2708             for (index = 0; index < elm->obj->init_array_num; index++) {
2709                 if (init_addr[index] != 0 && init_addr[index] != 1) {
2710                     dbg("calling init function for %s at %p", elm->obj->path,
2711                         (void *)init_addr[index]);
2712                     LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2713                         (void *)init_addr[index], 0, 0, elm->obj->path);
2714                     call_init_pointer(elm->obj, init_addr[index]);
2715                 }
2716             }
2717         }
2718         wlock_acquire(rtld_bind_lock, lockstate);
2719         unhold_object(elm->obj);
2720     }
2721     errmsg_restore(saved_msg);
2722 }
2723
2724 static void
2725 objlist_clear(Objlist *list)
2726 {
2727     Objlist_Entry *elm;
2728
2729     while (!STAILQ_EMPTY(list)) {
2730         elm = STAILQ_FIRST(list);
2731         STAILQ_REMOVE_HEAD(list, link);
2732         free(elm);
2733     }
2734 }
2735
2736 static Objlist_Entry *
2737 objlist_find(Objlist *list, const Obj_Entry *obj)
2738 {
2739     Objlist_Entry *elm;
2740
2741     STAILQ_FOREACH(elm, list, link)
2742         if (elm->obj == obj)
2743             return elm;
2744     return NULL;
2745 }
2746
2747 static void
2748 objlist_init(Objlist *list)
2749 {
2750     STAILQ_INIT(list);
2751 }
2752
2753 static void
2754 objlist_push_head(Objlist *list, Obj_Entry *obj)
2755 {
2756     Objlist_Entry *elm;
2757
2758     elm = NEW(Objlist_Entry);
2759     elm->obj = obj;
2760     STAILQ_INSERT_HEAD(list, elm, link);
2761 }
2762
2763 static void
2764 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2765 {
2766     Objlist_Entry *elm;
2767
2768     elm = NEW(Objlist_Entry);
2769     elm->obj = obj;
2770     STAILQ_INSERT_TAIL(list, elm, link);
2771 }
2772
2773 static void
2774 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
2775 {
2776         Objlist_Entry *elm, *listelm;
2777
2778         STAILQ_FOREACH(listelm, list, link) {
2779                 if (listelm->obj == listobj)
2780                         break;
2781         }
2782         elm = NEW(Objlist_Entry);
2783         elm->obj = obj;
2784         if (listelm != NULL)
2785                 STAILQ_INSERT_AFTER(list, listelm, elm, link);
2786         else
2787                 STAILQ_INSERT_TAIL(list, elm, link);
2788 }
2789
2790 static void
2791 objlist_remove(Objlist *list, Obj_Entry *obj)
2792 {
2793     Objlist_Entry *elm;
2794
2795     if ((elm = objlist_find(list, obj)) != NULL) {
2796         STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2797         free(elm);
2798     }
2799 }
2800
2801 /*
2802  * Relocate dag rooted in the specified object.
2803  * Returns 0 on success, or -1 on failure.
2804  */
2805
2806 static int
2807 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2808     int flags, RtldLockState *lockstate)
2809 {
2810         Objlist_Entry *elm;
2811         int error;
2812
2813         error = 0;
2814         STAILQ_FOREACH(elm, &root->dagmembers, link) {
2815                 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2816                     lockstate);
2817                 if (error == -1)
2818                         break;
2819         }
2820         return (error);
2821 }
2822
2823 /*
2824  * Prepare for, or clean after, relocating an object marked with
2825  * DT_TEXTREL or DF_TEXTREL.  Before relocating, all read-only
2826  * segments are remapped read-write.  After relocations are done, the
2827  * segment's permissions are returned back to the modes specified in
2828  * the phdrs.  If any relocation happened, or always for wired
2829  * program, COW is triggered.
2830  */
2831 static int
2832 reloc_textrel_prot(Obj_Entry *obj, bool before)
2833 {
2834         const Elf_Phdr *ph;
2835         void *base;
2836         size_t l, sz;
2837         int prot;
2838
2839         for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
2840             l--, ph++) {
2841                 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
2842                         continue;
2843                 base = obj->relocbase + trunc_page(ph->p_vaddr);
2844                 sz = round_page(ph->p_vaddr + ph->p_filesz) -
2845                     trunc_page(ph->p_vaddr);
2846                 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0);
2847                 if (mprotect(base, sz, prot) == -1) {
2848                         _rtld_error("%s: Cannot write-%sable text segment: %s",
2849                             obj->path, before ? "en" : "dis",
2850                             rtld_strerror(errno));
2851                         return (-1);
2852                 }
2853         }
2854         return (0);
2855 }
2856
2857 /*
2858  * Relocate single object.
2859  * Returns 0 on success, or -1 on failure.
2860  */
2861 static int
2862 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2863     int flags, RtldLockState *lockstate)
2864 {
2865
2866         if (obj->relocated)
2867                 return (0);
2868         obj->relocated = true;
2869         if (obj != rtldobj)
2870                 dbg("relocating \"%s\"", obj->path);
2871
2872         if (obj->symtab == NULL || obj->strtab == NULL ||
2873             !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2874                 _rtld_error("%s: Shared object has no run-time symbol table",
2875                             obj->path);
2876                 return (-1);
2877         }
2878
2879         /* There are relocations to the write-protected text segment. */
2880         if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
2881                 return (-1);
2882
2883         /* Process the non-PLT non-IFUNC relocations. */
2884         if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2885                 return (-1);
2886
2887         /* Re-protected the text segment. */
2888         if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
2889                 return (-1);
2890
2891         /* Set the special PLT or GOT entries. */
2892         init_pltgot(obj);
2893
2894         /* Process the PLT relocations. */
2895         if (reloc_plt(obj, flags, lockstate) == -1)
2896                 return (-1);
2897         /* Relocate the jump slots if we are doing immediate binding. */
2898         if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
2899             lockstate) == -1)
2900                 return (-1);
2901
2902         if (!obj->mainprog && obj_enforce_relro(obj) == -1)
2903                 return (-1);
2904
2905         /*
2906          * Set up the magic number and version in the Obj_Entry.  These
2907          * were checked in the crt1.o from the original ElfKit, so we
2908          * set them for backward compatibility.
2909          */
2910         obj->magic = RTLD_MAGIC;
2911         obj->version = RTLD_VERSION;
2912
2913         return (0);
2914 }
2915
2916 /*
2917  * Relocate newly-loaded shared objects.  The argument is a pointer to
2918  * the Obj_Entry for the first such object.  All objects from the first
2919  * to the end of the list of objects are relocated.  Returns 0 on success,
2920  * or -1 on failure.
2921  */
2922 static int
2923 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2924     int flags, RtldLockState *lockstate)
2925 {
2926         Obj_Entry *obj;
2927         int error;
2928
2929         for (error = 0, obj = first;  obj != NULL;
2930             obj = TAILQ_NEXT(obj, next)) {
2931                 if (obj->marker)
2932                         continue;
2933                 error = relocate_object(obj, bind_now, rtldobj, flags,
2934                     lockstate);
2935                 if (error == -1)
2936                         break;
2937         }
2938         return (error);
2939 }
2940
2941 /*
2942  * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2943  * referencing STT_GNU_IFUNC symbols is postponed till the other
2944  * relocations are done.  The indirect functions specified as
2945  * ifunc are allowed to call other symbols, so we need to have
2946  * objects relocated before asking for resolution from indirects.
2947  *
2948  * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2949  * instead of the usual lazy handling of PLT slots.  It is
2950  * consistent with how GNU does it.
2951  */
2952 static int
2953 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2954     RtldLockState *lockstate)
2955 {
2956
2957         if (obj->ifuncs_resolved)
2958                 return (0);
2959         obj->ifuncs_resolved = true;
2960         if (!obj->irelative && !((obj->bind_now || bind_now) && obj->gnu_ifunc))
2961                 return (0);
2962         if (obj_disable_relro(obj) == -1 ||
2963             (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
2964             ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2965             reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
2966             obj_enforce_relro(obj) == -1)
2967                 return (-1);
2968         return (0);
2969 }
2970
2971 static int
2972 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2973     RtldLockState *lockstate)
2974 {
2975         Objlist_Entry *elm;
2976         Obj_Entry *obj;
2977
2978         STAILQ_FOREACH(elm, list, link) {
2979                 obj = elm->obj;
2980                 if (obj->marker)
2981                         continue;
2982                 if (resolve_object_ifunc(obj, bind_now, flags,
2983                     lockstate) == -1)
2984                         return (-1);
2985         }
2986         return (0);
2987 }
2988
2989 /*
2990  * Cleanup procedure.  It will be called (by the atexit mechanism) just
2991  * before the process exits.
2992  */
2993 static void
2994 rtld_exit(void)
2995 {
2996     RtldLockState lockstate;
2997
2998     wlock_acquire(rtld_bind_lock, &lockstate);
2999     dbg("rtld_exit()");
3000     objlist_call_fini(&list_fini, NULL, &lockstate);
3001     /* No need to remove the items from the list, since we are exiting. */
3002     if (!libmap_disable)
3003         lm_fini();
3004     lock_release(rtld_bind_lock, &lockstate);
3005 }
3006
3007 /*
3008  * Iterate over a search path, translate each element, and invoke the
3009  * callback on the result.
3010  */
3011 static void *
3012 path_enumerate(const char *path, path_enum_proc callback,
3013     const char *refobj_path, void *arg)
3014 {
3015     const char *trans;
3016     if (path == NULL)
3017         return (NULL);
3018
3019     path += strspn(path, ":;");
3020     while (*path != '\0') {
3021         size_t len;
3022         char  *res;
3023
3024         len = strcspn(path, ":;");
3025         trans = lm_findn(refobj_path, path, len);
3026         if (trans)
3027             res = callback(trans, strlen(trans), arg);
3028         else
3029             res = callback(path, len, arg);
3030
3031         if (res != NULL)
3032             return (res);
3033
3034         path += len;
3035         path += strspn(path, ":;");
3036     }
3037
3038     return (NULL);
3039 }
3040
3041 struct try_library_args {
3042     const char  *name;
3043     size_t       namelen;
3044     char        *buffer;
3045     size_t       buflen;
3046     int          fd;
3047 };
3048
3049 static void *
3050 try_library_path(const char *dir, size_t dirlen, void *param)
3051 {
3052     struct try_library_args *arg;
3053     int fd;
3054
3055     arg = param;
3056     if (*dir == '/' || trust) {
3057         char *pathname;
3058
3059         if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3060                 return (NULL);
3061
3062         pathname = arg->buffer;
3063         strncpy(pathname, dir, dirlen);
3064         pathname[dirlen] = '/';
3065         strcpy(pathname + dirlen + 1, arg->name);
3066
3067         dbg("  Trying \"%s\"", pathname);
3068         fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3069         if (fd >= 0) {
3070             dbg("  Opened \"%s\", fd %d", pathname, fd);
3071             pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3072             strcpy(pathname, arg->buffer);
3073             arg->fd = fd;
3074             return (pathname);
3075         } else {
3076             dbg("  Failed to open \"%s\": %s",
3077                 pathname, rtld_strerror(errno));
3078         }
3079     }
3080     return (NULL);
3081 }
3082
3083 static char *
3084 search_library_path(const char *name, const char *path,
3085     const char *refobj_path, int *fdp)
3086 {
3087     char *p;
3088     struct try_library_args arg;
3089
3090     if (path == NULL)
3091         return NULL;
3092
3093     arg.name = name;
3094     arg.namelen = strlen(name);
3095     arg.buffer = xmalloc(PATH_MAX);
3096     arg.buflen = PATH_MAX;
3097     arg.fd = -1;
3098
3099     p = path_enumerate(path, try_library_path, refobj_path, &arg);
3100     *fdp = arg.fd;
3101
3102     free(arg.buffer);
3103
3104     return (p);
3105 }
3106
3107
3108 /*
3109  * Finds the library with the given name using the directory descriptors
3110  * listed in the LD_LIBRARY_PATH_FDS environment variable.
3111  *
3112  * Returns a freshly-opened close-on-exec file descriptor for the library,
3113  * or -1 if the library cannot be found.
3114  */
3115 static char *
3116 search_library_pathfds(const char *name, const char *path, int *fdp)
3117 {
3118         char *envcopy, *fdstr, *found, *last_token;
3119         size_t len;
3120         int dirfd, fd;
3121
3122         dbg("%s('%s', '%s', fdp)", __func__, name, path);
3123
3124         /* Don't load from user-specified libdirs into setuid binaries. */
3125         if (!trust)
3126                 return (NULL);
3127
3128         /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3129         if (path == NULL)
3130                 return (NULL);
3131
3132         /* LD_LIBRARY_PATH_FDS only works with relative paths. */
3133         if (name[0] == '/') {
3134                 dbg("Absolute path (%s) passed to %s", name, __func__);
3135                 return (NULL);
3136         }
3137
3138         /*
3139          * Use strtok_r() to walk the FD:FD:FD list.  This requires a local
3140          * copy of the path, as strtok_r rewrites separator tokens
3141          * with '\0'.
3142          */
3143         found = NULL;
3144         envcopy = xstrdup(path);
3145         for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3146             fdstr = strtok_r(NULL, ":", &last_token)) {
3147                 dirfd = parse_integer(fdstr);
3148                 if (dirfd < 0) {
3149                         _rtld_error("failed to parse directory FD: '%s'",
3150                                 fdstr);
3151                         break;
3152                 }
3153                 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3154                 if (fd >= 0) {
3155                         *fdp = fd;
3156                         len = strlen(fdstr) + strlen(name) + 3;
3157                         found = xmalloc(len);
3158                         if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3159                                 _rtld_error("error generating '%d/%s'",
3160                                     dirfd, name);
3161                                 rtld_die();
3162                         }
3163                         dbg("open('%s') => %d", found, fd);
3164                         break;
3165                 }
3166         }
3167         free(envcopy);
3168
3169         return (found);
3170 }
3171
3172
3173 int
3174 dlclose(void *handle)
3175 {
3176         RtldLockState lockstate;
3177         int error;
3178
3179         wlock_acquire(rtld_bind_lock, &lockstate);
3180         error = dlclose_locked(handle, &lockstate);
3181         lock_release(rtld_bind_lock, &lockstate);
3182         return (error);
3183 }
3184
3185 static int
3186 dlclose_locked(void *handle, RtldLockState *lockstate)
3187 {
3188     Obj_Entry *root;
3189
3190     root = dlcheck(handle);
3191     if (root == NULL)
3192         return -1;
3193     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3194         root->path);
3195
3196     /* Unreference the object and its dependencies. */
3197     root->dl_refcount--;
3198
3199     if (root->refcount == 1) {
3200         /*
3201          * The object will be no longer referenced, so we must unload it.
3202          * First, call the fini functions.
3203          */
3204         objlist_call_fini(&list_fini, root, lockstate);
3205
3206         unref_dag(root);
3207
3208         /* Finish cleaning up the newly-unreferenced objects. */
3209         GDB_STATE(RT_DELETE,&root->linkmap);
3210         unload_object(root, lockstate);
3211         GDB_STATE(RT_CONSISTENT,NULL);
3212     } else
3213         unref_dag(root);
3214
3215     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3216     return 0;
3217 }
3218
3219 char *
3220 dlerror(void)
3221 {
3222     char *msg = error_message;
3223     error_message = NULL;
3224     return msg;
3225 }
3226
3227 /*
3228  * This function is deprecated and has no effect.
3229  */
3230 void
3231 dllockinit(void *context,
3232     void *(*_lock_create)(void *context) __unused,
3233     void (*_rlock_acquire)(void *lock) __unused,
3234     void (*_wlock_acquire)(void *lock)  __unused,
3235     void (*_lock_release)(void *lock) __unused,
3236     void (*_lock_destroy)(void *lock) __unused,
3237     void (*context_destroy)(void *context))
3238 {
3239     static void *cur_context;
3240     static void (*cur_context_destroy)(void *);
3241
3242     /* Just destroy the context from the previous call, if necessary. */
3243     if (cur_context_destroy != NULL)
3244         cur_context_destroy(cur_context);
3245     cur_context = context;
3246     cur_context_destroy = context_destroy;
3247 }
3248
3249 void *
3250 dlopen(const char *name, int mode)
3251 {
3252
3253         return (rtld_dlopen(name, -1, mode));
3254 }
3255
3256 void *
3257 fdlopen(int fd, int mode)
3258 {
3259
3260         return (rtld_dlopen(NULL, fd, mode));
3261 }
3262
3263 static void *
3264 rtld_dlopen(const char *name, int fd, int mode)
3265 {
3266     RtldLockState lockstate;
3267     int lo_flags;
3268
3269     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3270     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3271     if (ld_tracing != NULL) {
3272         rlock_acquire(rtld_bind_lock, &lockstate);
3273         if (sigsetjmp(lockstate.env, 0) != 0)
3274             lock_upgrade(rtld_bind_lock, &lockstate);
3275         environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3276         lock_release(rtld_bind_lock, &lockstate);
3277     }
3278     lo_flags = RTLD_LO_DLOPEN;
3279     if (mode & RTLD_NODELETE)
3280             lo_flags |= RTLD_LO_NODELETE;
3281     if (mode & RTLD_NOLOAD)
3282             lo_flags |= RTLD_LO_NOLOAD;
3283     if (ld_tracing != NULL)
3284             lo_flags |= RTLD_LO_TRACE;
3285
3286     return (dlopen_object(name, fd, obj_main, lo_flags,
3287       mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3288 }
3289
3290 static void
3291 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3292 {
3293
3294         obj->dl_refcount--;
3295         unref_dag(obj);
3296         if (obj->refcount == 0)
3297                 unload_object(obj, lockstate);
3298 }
3299
3300 static Obj_Entry *
3301 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3302     int mode, RtldLockState *lockstate)
3303 {
3304     Obj_Entry *old_obj_tail;
3305     Obj_Entry *obj;
3306     Objlist initlist;
3307     RtldLockState mlockstate;
3308     int result;
3309
3310     objlist_init(&initlist);
3311
3312     if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3313         wlock_acquire(rtld_bind_lock, &mlockstate);
3314         lockstate = &mlockstate;
3315     }
3316     GDB_STATE(RT_ADD,NULL);
3317
3318     old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q));
3319     obj = NULL;
3320     if (name == NULL && fd == -1) {
3321         obj = obj_main;
3322         obj->refcount++;
3323     } else {
3324         obj = load_object(name, fd, refobj, lo_flags);
3325     }
3326
3327     if (obj) {
3328         obj->dl_refcount++;
3329         if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3330             objlist_push_tail(&list_global, obj);
3331         if (globallist_next(old_obj_tail) != NULL) {
3332             /* We loaded something new. */
3333             assert(globallist_next(old_obj_tail) == obj);
3334             result = 0;
3335             if ((lo_flags & RTLD_LO_EARLY) == 0 && obj->static_tls &&
3336               !allocate_tls_offset(obj)) {
3337                 _rtld_error("%s: No space available "
3338                   "for static Thread Local Storage", obj->path);
3339                 result = -1;
3340             }
3341             if (result != -1)
3342                 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3343                     RTLD_LO_EARLY));
3344             init_dag(obj);
3345             ref_dag(obj);
3346             if (result != -1)
3347                 result = rtld_verify_versions(&obj->dagmembers);
3348             if (result != -1 && ld_tracing)
3349                 goto trace;
3350             if (result == -1 || relocate_object_dag(obj,
3351               (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3352               (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3353               lockstate) == -1) {
3354                 dlopen_cleanup(obj, lockstate);
3355                 obj = NULL;
3356             } else if (lo_flags & RTLD_LO_EARLY) {
3357                 /*
3358                  * Do not call the init functions for early loaded
3359                  * filtees.  The image is still not initialized enough
3360                  * for them to work.
3361                  *
3362                  * Our object is found by the global object list and
3363                  * will be ordered among all init calls done right
3364                  * before transferring control to main.
3365                  */
3366             } else {
3367                 /* Make list of init functions to call. */
3368                 initlist_add_objects(obj, obj, &initlist);
3369             }
3370             /*
3371              * Process all no_delete or global objects here, given
3372              * them own DAGs to prevent their dependencies from being
3373              * unloaded.  This has to be done after we have loaded all
3374              * of the dependencies, so that we do not miss any.
3375              */
3376             if (obj != NULL)
3377                 process_z(obj);
3378         } else {
3379             /*
3380              * Bump the reference counts for objects on this DAG.  If
3381              * this is the first dlopen() call for the object that was
3382              * already loaded as a dependency, initialize the dag
3383              * starting at it.
3384              */
3385             init_dag(obj);
3386             ref_dag(obj);
3387
3388             if ((lo_flags & RTLD_LO_TRACE) != 0)
3389                 goto trace;
3390         }
3391         if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3392           obj->z_nodelete) && !obj->ref_nodel) {
3393             dbg("obj %s nodelete", obj->path);
3394             ref_dag(obj);
3395             obj->z_nodelete = obj->ref_nodel = true;
3396         }
3397     }
3398
3399     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3400         name);
3401     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3402
3403     if ((lo_flags & RTLD_LO_EARLY) == 0) {
3404         map_stacks_exec(lockstate);
3405         if (obj != NULL)
3406             distribute_static_tls(&initlist, lockstate);
3407     }
3408
3409     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3410       (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3411       lockstate) == -1) {
3412         objlist_clear(&initlist);
3413         dlopen_cleanup(obj, lockstate);
3414         if (lockstate == &mlockstate)
3415             lock_release(rtld_bind_lock, lockstate);
3416         return (NULL);
3417     }
3418
3419     if (!(lo_flags & RTLD_LO_EARLY)) {
3420         /* Call the init functions. */
3421         objlist_call_init(&initlist, lockstate);
3422     }
3423     objlist_clear(&initlist);
3424     if (lockstate == &mlockstate)
3425         lock_release(rtld_bind_lock, lockstate);
3426     return obj;
3427 trace:
3428     trace_loaded_objects(obj);
3429     if (lockstate == &mlockstate)
3430         lock_release(rtld_bind_lock, lockstate);
3431     exit(0);
3432 }
3433
3434 static void *
3435 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3436     int flags)
3437 {
3438     DoneList donelist;
3439     const Obj_Entry *obj, *defobj;
3440     const Elf_Sym *def;
3441     SymLook req;
3442     RtldLockState lockstate;
3443     tls_index ti;
3444     void *sym;
3445     int res;
3446
3447     def = NULL;
3448     defobj = NULL;
3449     symlook_init(&req, name);
3450     req.ventry = ve;
3451     req.flags = flags | SYMLOOK_IN_PLT;
3452     req.lockstate = &lockstate;
3453
3454     LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3455     rlock_acquire(rtld_bind_lock, &lockstate);
3456     if (sigsetjmp(lockstate.env, 0) != 0)
3457             lock_upgrade(rtld_bind_lock, &lockstate);
3458     if (handle == NULL || handle == RTLD_NEXT ||
3459         handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3460
3461         if ((obj = obj_from_addr(retaddr)) == NULL) {
3462             _rtld_error("Cannot determine caller's shared object");
3463             lock_release(rtld_bind_lock, &lockstate);
3464             LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3465             return NULL;
3466         }
3467         if (handle == NULL) {   /* Just the caller's shared object. */
3468             res = symlook_obj(&req, obj);
3469             if (res == 0) {
3470                 def = req.sym_out;
3471                 defobj = req.defobj_out;
3472             }
3473         } else if (handle == RTLD_NEXT || /* Objects after caller's */
3474                    handle == RTLD_SELF) { /* ... caller included */
3475             if (handle == RTLD_NEXT)
3476                 obj = globallist_next(obj);
3477             for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3478                 if (obj->marker)
3479                     continue;
3480                 res = symlook_obj(&req, obj);
3481                 if (res == 0) {
3482                     if (def == NULL ||
3483                       ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
3484                         def = req.sym_out;
3485                         defobj = req.defobj_out;
3486                         if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3487                             break;
3488                     }
3489                 }
3490             }
3491             /*
3492              * Search the dynamic linker itself, and possibly resolve the
3493              * symbol from there.  This is how the application links to
3494              * dynamic linker services such as dlopen.
3495              */
3496             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3497                 res = symlook_obj(&req, &obj_rtld);
3498                 if (res == 0) {
3499                     def = req.sym_out;
3500                     defobj = req.defobj_out;
3501                 }
3502             }
3503         } else {
3504             assert(handle == RTLD_DEFAULT);
3505             res = symlook_default(&req, obj);
3506             if (res == 0) {
3507                 defobj = req.defobj_out;
3508                 def = req.sym_out;
3509             }
3510         }
3511     } else {
3512         if ((obj = dlcheck(handle)) == NULL) {
3513             lock_release(rtld_bind_lock, &lockstate);
3514             LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3515             return NULL;
3516         }
3517
3518         donelist_init(&donelist);
3519         if (obj->mainprog) {
3520             /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3521             res = symlook_global(&req, &donelist);
3522             if (res == 0) {
3523                 def = req.sym_out;
3524                 defobj = req.defobj_out;
3525             }
3526             /*
3527              * Search the dynamic linker itself, and possibly resolve the
3528              * symbol from there.  This is how the application links to
3529              * dynamic linker services such as dlopen.
3530              */
3531             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3532                 res = symlook_obj(&req, &obj_rtld);
3533                 if (res == 0) {
3534                     def = req.sym_out;
3535                     defobj = req.defobj_out;
3536                 }
3537             }
3538         }
3539         else {
3540             /* Search the whole DAG rooted at the given object. */
3541             res = symlook_list(&req, &obj->dagmembers, &donelist);
3542             if (res == 0) {
3543                 def = req.sym_out;
3544                 defobj = req.defobj_out;
3545             }
3546         }
3547     }
3548
3549     if (def != NULL) {
3550         lock_release(rtld_bind_lock, &lockstate);
3551
3552         /*
3553          * The value required by the caller is derived from the value
3554          * of the symbol. this is simply the relocated value of the
3555          * symbol.
3556          */
3557         if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
3558             sym = make_function_pointer(def, defobj);
3559         else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
3560             sym = rtld_resolve_ifunc(defobj, def);
3561         else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
3562             ti.ti_module = defobj->tlsindex;
3563             ti.ti_offset = def->st_value;
3564             sym = __tls_get_addr(&ti);
3565         } else
3566             sym = defobj->relocbase + def->st_value;
3567         LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
3568         return (sym);
3569     }
3570
3571     _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
3572       ve != NULL ? ve->name : "");
3573     lock_release(rtld_bind_lock, &lockstate);
3574     LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3575     return NULL;
3576 }
3577
3578 void *
3579 dlsym(void *handle, const char *name)
3580 {
3581         return do_dlsym(handle, name, __builtin_return_address(0), NULL,
3582             SYMLOOK_DLSYM);
3583 }
3584
3585 dlfunc_t
3586 dlfunc(void *handle, const char *name)
3587 {
3588         union {
3589                 void *d;
3590                 dlfunc_t f;
3591         } rv;
3592
3593         rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
3594             SYMLOOK_DLSYM);
3595         return (rv.f);
3596 }
3597
3598 void *
3599 dlvsym(void *handle, const char *name, const char *version)
3600 {
3601         Ver_Entry ventry;
3602
3603         ventry.name = version;
3604         ventry.file = NULL;
3605         ventry.hash = elf_hash(version);
3606         ventry.flags= 0;
3607         return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
3608             SYMLOOK_DLSYM);
3609 }
3610
3611 int
3612 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
3613 {
3614     const Obj_Entry *obj;
3615     RtldLockState lockstate;
3616
3617     rlock_acquire(rtld_bind_lock, &lockstate);
3618     obj = obj_from_addr(addr);
3619     if (obj == NULL) {
3620         _rtld_error("No shared object contains address");
3621         lock_release(rtld_bind_lock, &lockstate);
3622         return (0);
3623     }
3624     rtld_fill_dl_phdr_info(obj, phdr_info);
3625     lock_release(rtld_bind_lock, &lockstate);
3626     return (1);
3627 }
3628
3629 int
3630 dladdr(const void *addr, Dl_info *info)
3631 {
3632     const Obj_Entry *obj;
3633     const Elf_Sym *def;
3634     void *symbol_addr;
3635     unsigned long symoffset;
3636     RtldLockState lockstate;
3637
3638     rlock_acquire(rtld_bind_lock, &lockstate);
3639     obj = obj_from_addr(addr);
3640     if (obj == NULL) {
3641         _rtld_error("No shared object contains address");
3642         lock_release(rtld_bind_lock, &lockstate);
3643         return 0;
3644     }
3645     info->dli_fname = obj->path;
3646     info->dli_fbase = obj->mapbase;
3647     info->dli_saddr = (void *)0;
3648     info->dli_sname = NULL;
3649
3650     /*
3651      * Walk the symbol list looking for the symbol whose address is
3652      * closest to the address sent in.
3653      */
3654     for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
3655         def = obj->symtab + symoffset;
3656
3657         /*
3658          * For skip the symbol if st_shndx is either SHN_UNDEF or
3659          * SHN_COMMON.
3660          */
3661         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
3662             continue;
3663
3664         /*
3665          * If the symbol is greater than the specified address, or if it
3666          * is further away from addr than the current nearest symbol,
3667          * then reject it.
3668          */
3669         symbol_addr = obj->relocbase + def->st_value;
3670         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
3671             continue;
3672
3673         /* Update our idea of the nearest symbol. */
3674         info->dli_sname = obj->strtab + def->st_name;
3675         info->dli_saddr = symbol_addr;
3676
3677         /* Exact match? */
3678         if (info->dli_saddr == addr)
3679             break;
3680     }
3681     lock_release(rtld_bind_lock, &lockstate);
3682     return 1;
3683 }
3684
3685 int
3686 dlinfo(void *handle, int request, void *p)
3687 {
3688     const Obj_Entry *obj;
3689     RtldLockState lockstate;
3690     int error;
3691
3692     rlock_acquire(rtld_bind_lock, &lockstate);
3693
3694     if (handle == NULL || handle == RTLD_SELF) {
3695         void *retaddr;
3696
3697         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
3698         if ((obj = obj_from_addr(retaddr)) == NULL)
3699             _rtld_error("Cannot determine caller's shared object");
3700     } else
3701         obj = dlcheck(handle);
3702
3703     if (obj == NULL) {
3704         lock_release(rtld_bind_lock, &lockstate);
3705         return (-1);
3706     }
3707
3708     error = 0;
3709     switch (request) {
3710     case RTLD_DI_LINKMAP:
3711         *((struct link_map const **)p) = &obj->linkmap;
3712         break;
3713     case RTLD_DI_ORIGIN:
3714         error = rtld_dirname(obj->path, p);
3715         break;
3716
3717     case RTLD_DI_SERINFOSIZE:
3718     case RTLD_DI_SERINFO:
3719         error = do_search_info(obj, request, (struct dl_serinfo *)p);
3720         break;
3721
3722     default:
3723         _rtld_error("Invalid request %d passed to dlinfo()", request);
3724         error = -1;
3725     }
3726
3727     lock_release(rtld_bind_lock, &lockstate);
3728
3729     return (error);
3730 }
3731
3732 static void
3733 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3734 {
3735
3736         phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3737         phdr_info->dlpi_name = obj->path;
3738         phdr_info->dlpi_phdr = obj->phdr;
3739         phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3740         phdr_info->dlpi_tls_modid = obj->tlsindex;
3741         phdr_info->dlpi_tls_data = obj->tlsinit;
3742         phdr_info->dlpi_adds = obj_loads;
3743         phdr_info->dlpi_subs = obj_loads - obj_count;
3744 }
3745
3746 int
3747 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3748 {
3749         struct dl_phdr_info phdr_info;
3750         Obj_Entry *obj, marker;
3751         RtldLockState bind_lockstate, phdr_lockstate;
3752         int error;
3753
3754         init_marker(&marker);
3755         error = 0;
3756
3757         wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3758         wlock_acquire(rtld_bind_lock, &bind_lockstate);
3759         for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
3760                 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
3761                 rtld_fill_dl_phdr_info(obj, &phdr_info);
3762                 hold_object(obj);
3763                 lock_release(rtld_bind_lock, &bind_lockstate);
3764
3765                 error = callback(&phdr_info, sizeof phdr_info, param);
3766
3767                 wlock_acquire(rtld_bind_lock, &bind_lockstate);
3768                 unhold_object(obj);
3769                 obj = globallist_next(&marker);
3770                 TAILQ_REMOVE(&obj_list, &marker, next);
3771                 if (error != 0) {
3772                         lock_release(rtld_bind_lock, &bind_lockstate);
3773                         lock_release(rtld_phdr_lock, &phdr_lockstate);
3774                         return (error);
3775                 }
3776         }
3777
3778         if (error == 0) {
3779                 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
3780                 lock_release(rtld_bind_lock, &bind_lockstate);
3781                 error = callback(&phdr_info, sizeof(phdr_info), param);
3782         }
3783         lock_release(rtld_phdr_lock, &phdr_lockstate);
3784         return (error);
3785 }
3786
3787 static void *
3788 fill_search_info(const char *dir, size_t dirlen, void *param)
3789 {
3790     struct fill_search_info_args *arg;
3791
3792     arg = param;
3793
3794     if (arg->request == RTLD_DI_SERINFOSIZE) {
3795         arg->serinfo->dls_cnt ++;
3796         arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
3797     } else {
3798         struct dl_serpath *s_entry;
3799
3800         s_entry = arg->serpath;
3801         s_entry->dls_name  = arg->strspace;
3802         s_entry->dls_flags = arg->flags;
3803
3804         strncpy(arg->strspace, dir, dirlen);
3805         arg->strspace[dirlen] = '\0';
3806
3807         arg->strspace += dirlen + 1;
3808         arg->serpath++;
3809     }
3810
3811     return (NULL);
3812 }
3813
3814 static int
3815 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3816 {
3817     struct dl_serinfo _info;
3818     struct fill_search_info_args args;
3819
3820     args.request = RTLD_DI_SERINFOSIZE;
3821     args.serinfo = &_info;
3822
3823     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3824     _info.dls_cnt  = 0;
3825
3826     path_enumerate(obj->rpath, fill_search_info, NULL, &args);
3827     path_enumerate(ld_library_path, fill_search_info, NULL, &args);
3828     path_enumerate(obj->runpath, fill_search_info, NULL, &args);
3829     path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
3830     if (!obj->z_nodeflib)
3831       path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
3832
3833
3834     if (request == RTLD_DI_SERINFOSIZE) {
3835         info->dls_size = _info.dls_size;
3836         info->dls_cnt = _info.dls_cnt;
3837         return (0);
3838     }
3839
3840     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3841         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3842         return (-1);
3843     }
3844
3845     args.request  = RTLD_DI_SERINFO;
3846     args.serinfo  = info;
3847     args.serpath  = &info->dls_serpath[0];
3848     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3849
3850     args.flags = LA_SER_RUNPATH;
3851     if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
3852         return (-1);
3853
3854     args.flags = LA_SER_LIBPATH;
3855     if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
3856         return (-1);
3857
3858     args.flags = LA_SER_RUNPATH;
3859     if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
3860         return (-1);
3861
3862     args.flags = LA_SER_CONFIG;
3863     if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
3864       != NULL)
3865         return (-1);
3866
3867     args.flags = LA_SER_DEFAULT;
3868     if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
3869       fill_search_info, NULL, &args) != NULL)
3870         return (-1);
3871     return (0);
3872 }
3873
3874 static int
3875 rtld_dirname(const char *path, char *bname)
3876 {
3877     const char *endp;
3878
3879     /* Empty or NULL string gets treated as "." */
3880     if (path == NULL || *path == '\0') {
3881         bname[0] = '.';
3882         bname[1] = '\0';
3883         return (0);
3884     }
3885
3886     /* Strip trailing slashes */
3887     endp = path + strlen(path) - 1;
3888     while (endp > path && *endp == '/')
3889         endp--;
3890
3891     /* Find the start of the dir */
3892     while (endp > path && *endp != '/')
3893         endp--;
3894
3895     /* Either the dir is "/" or there are no slashes */
3896     if (endp == path) {
3897         bname[0] = *endp == '/' ? '/' : '.';
3898         bname[1] = '\0';
3899         return (0);
3900     } else {
3901         do {
3902             endp--;
3903         } while (endp > path && *endp == '/');
3904     }
3905
3906     if (endp - path + 2 > PATH_MAX)
3907     {
3908         _rtld_error("Filename is too long: %s", path);
3909         return(-1);
3910     }
3911
3912     strncpy(bname, path, endp - path + 1);
3913     bname[endp - path + 1] = '\0';
3914     return (0);
3915 }
3916
3917 static int
3918 rtld_dirname_abs(const char *path, char *base)
3919 {
3920         char *last;
3921
3922         if (realpath(path, base) == NULL)
3923                 return (-1);
3924         dbg("%s -> %s", path, base);
3925         last = strrchr(base, '/');
3926         if (last == NULL)
3927                 return (-1);
3928         if (last != base)
3929                 *last = '\0';
3930         return (0);
3931 }
3932
3933 static void
3934 linkmap_add(Obj_Entry *obj)
3935 {
3936     struct link_map *l = &obj->linkmap;
3937     struct link_map *prev;
3938
3939     obj->linkmap.l_name = obj->path;
3940     obj->linkmap.l_addr = obj->mapbase;
3941     obj->linkmap.l_ld = obj->dynamic;
3942 #ifdef __mips__
3943     /* GDB needs load offset on MIPS to use the symbols */
3944     obj->linkmap.l_offs = obj->relocbase;
3945 #endif
3946
3947     if (r_debug.r_map == NULL) {
3948         r_debug.r_map = l;
3949         return;
3950     }
3951
3952     /*
3953      * Scan to the end of the list, but not past the entry for the
3954      * dynamic linker, which we want to keep at the very end.
3955      */
3956     for (prev = r_debug.r_map;
3957       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3958       prev = prev->l_next)
3959         ;
3960
3961     /* Link in the new entry. */
3962     l->l_prev = prev;
3963     l->l_next = prev->l_next;
3964     if (l->l_next != NULL)
3965         l->l_next->l_prev = l;
3966     prev->l_next = l;
3967 }
3968
3969 static void
3970 linkmap_delete(Obj_Entry *obj)
3971 {
3972     struct link_map *l = &obj->linkmap;
3973
3974     if (l->l_prev == NULL) {
3975         if ((r_debug.r_map = l->l_next) != NULL)
3976             l->l_next->l_prev = NULL;
3977         return;
3978     }
3979
3980     if ((l->l_prev->l_next = l->l_next) != NULL)
3981         l->l_next->l_prev = l->l_prev;
3982 }
3983
3984 /*
3985  * Function for the debugger to set a breakpoint on to gain control.
3986  *
3987  * The two parameters allow the debugger to easily find and determine
3988  * what the runtime loader is doing and to whom it is doing it.
3989  *
3990  * When the loadhook trap is hit (r_debug_state, set at program
3991  * initialization), the arguments can be found on the stack:
3992  *
3993  *  +8   struct link_map *m
3994  *  +4   struct r_debug  *rd
3995  *  +0   RetAddr
3996  */
3997 void
3998 r_debug_state(struct r_debug* rd __unused, struct link_map *m  __unused)
3999 {
4000     /*
4001      * The following is a hack to force the compiler to emit calls to
4002      * this function, even when optimizing.  If the function is empty,
4003      * the compiler is not obliged to emit any code for calls to it,
4004      * even when marked __noinline.  However, gdb depends on those
4005      * calls being made.
4006      */
4007     __compiler_membar();
4008 }
4009
4010 /*
4011  * A function called after init routines have completed. This can be used to
4012  * break before a program's entry routine is called, and can be used when
4013  * main is not available in the symbol table.
4014  */
4015 void
4016 _r_debug_postinit(struct link_map *m __unused)
4017 {
4018
4019         /* See r_debug_state(). */
4020         __compiler_membar();
4021 }
4022
4023 static void
4024 release_object(Obj_Entry *obj)
4025 {
4026
4027         if (obj->holdcount > 0) {
4028                 obj->unholdfree = true;
4029                 return;
4030         }
4031         munmap(obj->mapbase, obj->mapsize);
4032         linkmap_delete(obj);
4033         obj_free(obj);
4034 }
4035
4036 /*
4037  * Get address of the pointer variable in the main program.
4038  * Prefer non-weak symbol over the weak one.
4039  */
4040 static const void **
4041 get_program_var_addr(const char *name, RtldLockState *lockstate)
4042 {
4043     SymLook req;
4044     DoneList donelist;
4045
4046     symlook_init(&req, name);
4047     req.lockstate = lockstate;
4048     donelist_init(&donelist);
4049     if (symlook_global(&req, &donelist) != 0)
4050         return (NULL);
4051     if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4052         return ((const void **)make_function_pointer(req.sym_out,
4053           req.defobj_out));
4054     else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4055         return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4056     else
4057         return ((const void **)(req.defobj_out->relocbase +
4058           req.sym_out->st_value));
4059 }
4060
4061 /*
4062  * Set a pointer variable in the main program to the given value.  This
4063  * is used to set key variables such as "environ" before any of the
4064  * init functions are called.
4065  */
4066 static void
4067 set_program_var(const char *name, const void *value)
4068 {
4069     const void **addr;
4070
4071     if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4072         dbg("\"%s\": *%p <-- %p", name, addr, value);
4073         *addr = value;
4074     }
4075 }
4076
4077 /*
4078  * Search the global objects, including dependencies and main object,
4079  * for the given symbol.
4080  */
4081 static int
4082 symlook_global(SymLook *req, DoneList *donelist)
4083 {
4084     SymLook req1;
4085     const Objlist_Entry *elm;
4086     int res;
4087
4088     symlook_init_from_req(&req1, req);
4089
4090     /* Search all objects loaded at program start up. */
4091     if (req->defobj_out == NULL ||
4092       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4093         res = symlook_list(&req1, &list_main, donelist);
4094         if (res == 0 && (req->defobj_out == NULL ||
4095           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4096             req->sym_out = req1.sym_out;
4097             req->defobj_out = req1.defobj_out;
4098             assert(req->defobj_out != NULL);
4099         }
4100     }
4101
4102     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4103     STAILQ_FOREACH(elm, &list_global, link) {
4104         if (req->defobj_out != NULL &&
4105           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4106             break;
4107         res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4108         if (res == 0 && (req->defobj_out == NULL ||
4109           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4110             req->sym_out = req1.sym_out;
4111             req->defobj_out = req1.defobj_out;
4112             assert(req->defobj_out != NULL);
4113         }
4114     }
4115
4116     return (req->sym_out != NULL ? 0 : ESRCH);
4117 }
4118
4119 /*
4120  * Given a symbol name in a referencing object, find the corresponding
4121  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
4122  * no definition was found.  Returns a pointer to the Obj_Entry of the
4123  * defining object via the reference parameter DEFOBJ_OUT.
4124  */
4125 static int
4126 symlook_default(SymLook *req, const Obj_Entry *refobj)
4127 {
4128     DoneList donelist;
4129     const Objlist_Entry *elm;
4130     SymLook req1;
4131     int res;
4132
4133     donelist_init(&donelist);
4134     symlook_init_from_req(&req1, req);
4135
4136     /*
4137      * Look first in the referencing object if linked symbolically,
4138      * and similarly handle protected symbols.
4139      */
4140     res = symlook_obj(&req1, refobj);
4141     if (res == 0 && (refobj->symbolic ||
4142       ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4143         req->sym_out = req1.sym_out;
4144         req->defobj_out = req1.defobj_out;
4145         assert(req->defobj_out != NULL);
4146     }
4147     if (refobj->symbolic || req->defobj_out != NULL)
4148         donelist_check(&donelist, refobj);
4149
4150     symlook_global(req, &donelist);
4151
4152     /* Search all dlopened DAGs containing the referencing object. */
4153     STAILQ_FOREACH(elm, &refobj->dldags, link) {
4154         if (req->sym_out != NULL &&
4155           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
4156             break;
4157         res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4158         if (res == 0 && (req->sym_out == NULL ||
4159           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4160             req->sym_out = req1.sym_out;
4161             req->defobj_out = req1.defobj_out;
4162             assert(req->defobj_out != NULL);
4163         }
4164     }
4165
4166     /*
4167      * Search the dynamic linker itself, and possibly resolve the
4168      * symbol from there.  This is how the application links to
4169      * dynamic linker services such as dlopen.
4170      */
4171     if (req->sym_out == NULL ||
4172       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4173         res = symlook_obj(&req1, &obj_rtld);
4174         if (res == 0) {
4175             req->sym_out = req1.sym_out;
4176             req->defobj_out = req1.defobj_out;
4177             assert(req->defobj_out != NULL);
4178         }
4179     }
4180
4181     return (req->sym_out != NULL ? 0 : ESRCH);
4182 }
4183
4184 static int
4185 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4186 {
4187     const Elf_Sym *def;
4188     const Obj_Entry *defobj;
4189     const Objlist_Entry *elm;
4190     SymLook req1;
4191     int res;
4192
4193     def = NULL;
4194     defobj = NULL;
4195     STAILQ_FOREACH(elm, objlist, link) {
4196         if (donelist_check(dlp, elm->obj))
4197             continue;
4198         symlook_init_from_req(&req1, req);
4199         if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4200             if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4201                 def = req1.sym_out;
4202                 defobj = req1.defobj_out;
4203                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4204                     break;
4205             }
4206         }
4207     }
4208     if (def != NULL) {
4209         req->sym_out = def;
4210         req->defobj_out = defobj;
4211         return (0);
4212     }
4213     return (ESRCH);
4214 }
4215
4216 /*
4217  * Search the chain of DAGS cointed to by the given Needed_Entry
4218  * for a symbol of the given name.  Each DAG is scanned completely
4219  * before advancing to the next one.  Returns a pointer to the symbol,
4220  * or NULL if no definition was found.
4221  */
4222 static int
4223 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4224 {
4225     const Elf_Sym *def;
4226     const Needed_Entry *n;
4227     const Obj_Entry *defobj;
4228     SymLook req1;
4229     int res;
4230
4231     def = NULL;
4232     defobj = NULL;
4233     symlook_init_from_req(&req1, req);
4234     for (n = needed; n != NULL; n = n->next) {
4235         if (n->obj == NULL ||
4236             (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4237             continue;
4238         if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
4239             def = req1.sym_out;
4240             defobj = req1.defobj_out;
4241             if (ELF_ST_BIND(def->st_info) != STB_WEAK)
4242                 break;
4243         }
4244     }
4245     if (def != NULL) {
4246         req->sym_out = def;
4247         req->defobj_out = defobj;
4248         return (0);
4249     }
4250     return (ESRCH);
4251 }
4252
4253 /*
4254  * Search the symbol table of a single shared object for a symbol of
4255  * the given name and version, if requested.  Returns a pointer to the
4256  * symbol, or NULL if no definition was found.  If the object is
4257  * filter, return filtered symbol from filtee.
4258  *
4259  * The symbol's hash value is passed in for efficiency reasons; that
4260  * eliminates many recomputations of the hash value.
4261  */
4262 int
4263 symlook_obj(SymLook *req, const Obj_Entry *obj)
4264 {
4265     DoneList donelist;
4266     SymLook req1;
4267     int flags, res, mres;
4268
4269     /*
4270      * If there is at least one valid hash at this point, we prefer to
4271      * use the faster GNU version if available.
4272      */
4273     if (obj->valid_hash_gnu)
4274         mres = symlook_obj1_gnu(req, obj);
4275     else if (obj->valid_hash_sysv)
4276         mres = symlook_obj1_sysv(req, obj);
4277     else
4278         return (EINVAL);
4279
4280     if (mres == 0) {
4281         if (obj->needed_filtees != NULL) {
4282             flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4283             load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4284             donelist_init(&donelist);
4285             symlook_init_from_req(&req1, req);
4286             res = symlook_needed(&req1, obj->needed_filtees, &donelist);
4287             if (res == 0) {
4288                 req->sym_out = req1.sym_out;
4289                 req->defobj_out = req1.defobj_out;
4290             }
4291             return (res);
4292         }
4293         if (obj->needed_aux_filtees != NULL) {
4294             flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
4295             load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4296             donelist_init(&donelist);
4297             symlook_init_from_req(&req1, req);
4298             res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
4299             if (res == 0) {
4300                 req->sym_out = req1.sym_out;
4301                 req->defobj_out = req1.defobj_out;
4302                 return (res);
4303             }
4304         }
4305     }
4306     return (mres);
4307 }
4308
4309 /* Symbol match routine common to both hash functions */
4310 static bool
4311 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4312     const unsigned long symnum)
4313 {
4314         Elf_Versym verndx;
4315         const Elf_Sym *symp;
4316         const char *strp;
4317
4318         symp = obj->symtab + symnum;
4319         strp = obj->strtab + symp->st_name;
4320
4321         switch (ELF_ST_TYPE(symp->st_info)) {
4322         case STT_FUNC:
4323         case STT_NOTYPE:
4324         case STT_OBJECT:
4325         case STT_COMMON:
4326         case STT_GNU_IFUNC:
4327                 if (symp->st_value == 0)
4328                         return (false);
4329                 /* fallthrough */
4330         case STT_TLS:
4331                 if (symp->st_shndx != SHN_UNDEF)
4332                         break;
4333 #ifndef __mips__
4334                 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4335                     (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4336                         break;
4337 #endif
4338                 /* fallthrough */
4339         default:
4340                 return (false);
4341         }
4342         if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4343                 return (false);
4344
4345         if (req->ventry == NULL) {
4346                 if (obj->versyms != NULL) {
4347                         verndx = VER_NDX(obj->versyms[symnum]);
4348                         if (verndx > obj->vernum) {
4349                                 _rtld_error(
4350                                     "%s: symbol %s references wrong version %d",
4351                                     obj->path, obj->strtab + symnum, verndx);
4352                                 return (false);
4353                         }
4354                         /*
4355                          * If we are not called from dlsym (i.e. this
4356                          * is a normal relocation from unversioned
4357                          * binary), accept the symbol immediately if
4358                          * it happens to have first version after this
4359                          * shared object became versioned.  Otherwise,
4360                          * if symbol is versioned and not hidden,
4361                          * remember it. If it is the only symbol with
4362                          * this name exported by the shared object, it
4363                          * will be returned as a match by the calling
4364                          * function. If symbol is global (verndx < 2)
4365                          * accept it unconditionally.
4366                          */
4367                         if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4368                             verndx == VER_NDX_GIVEN) {
4369                                 result->sym_out = symp;
4370                                 return (true);
4371                         }
4372                         else if (verndx >= VER_NDX_GIVEN) {
4373                                 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4374                                     == 0) {
4375                                         if (result->vsymp == NULL)
4376                                                 result->vsymp = symp;
4377                                         result->vcount++;
4378                                 }
4379                                 return (false);
4380                         }
4381                 }
4382                 result->sym_out = symp;
4383                 return (true);
4384         }
4385         if (obj->versyms == NULL) {
4386                 if (object_match_name(obj, req->ventry->name)) {
4387                         _rtld_error("%s: object %s should provide version %s "
4388                             "for symbol %s", obj_rtld.path, obj->path,
4389                             req->ventry->name, obj->strtab + symnum);
4390                         return (false);
4391                 }
4392         } else {
4393                 verndx = VER_NDX(obj->versyms[symnum]);
4394                 if (verndx > obj->vernum) {
4395                         _rtld_error("%s: symbol %s references wrong version %d",
4396                             obj->path, obj->strtab + symnum, verndx);
4397                         return (false);
4398                 }
4399                 if (obj->vertab[verndx].hash != req->ventry->hash ||
4400                     strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4401                         /*
4402                          * Version does not match. Look if this is a
4403                          * global symbol and if it is not hidden. If
4404                          * global symbol (verndx < 2) is available,
4405                          * use it. Do not return symbol if we are
4406                          * called by dlvsym, because dlvsym looks for
4407                          * a specific version and default one is not
4408                          * what dlvsym wants.
4409                          */
4410                         if ((req->flags & SYMLOOK_DLSYM) ||
4411                             (verndx >= VER_NDX_GIVEN) ||
4412                             (obj->versyms[symnum] & VER_NDX_HIDDEN))
4413                                 return (false);
4414                 }
4415         }
4416         result->sym_out = symp;
4417         return (true);
4418 }
4419
4420 /*
4421  * Search for symbol using SysV hash function.
4422  * obj->buckets is known not to be NULL at this point; the test for this was
4423  * performed with the obj->valid_hash_sysv assignment.
4424  */
4425 static int
4426 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4427 {
4428         unsigned long symnum;
4429         Sym_Match_Result matchres;
4430
4431         matchres.sym_out = NULL;
4432         matchres.vsymp = NULL;
4433         matchres.vcount = 0;
4434
4435         for (symnum = obj->buckets[req->hash % obj->nbuckets];
4436             symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4437                 if (symnum >= obj->nchains)
4438                         return (ESRCH); /* Bad object */
4439
4440                 if (matched_symbol(req, obj, &matchres, symnum)) {
4441                         req->sym_out = matchres.sym_out;
4442                         req->defobj_out = obj;
4443                         return (0);
4444                 }
4445         }
4446         if (matchres.vcount == 1) {
4447                 req->sym_out = matchres.vsymp;
4448                 req->defobj_out = obj;
4449                 return (0);
4450         }
4451         return (ESRCH);
4452 }
4453
4454 /* Search for symbol using GNU hash function */
4455 static int
4456 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4457 {
4458         Elf_Addr bloom_word;
4459         const Elf32_Word *hashval;
4460         Elf32_Word bucket;
4461         Sym_Match_Result matchres;
4462         unsigned int h1, h2;
4463         unsigned long symnum;
4464
4465         matchres.sym_out = NULL;
4466         matchres.vsymp = NULL;
4467         matchres.vcount = 0;
4468
4469         /* Pick right bitmask word from Bloom filter array */
4470         bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4471             obj->maskwords_bm_gnu];
4472
4473         /* Calculate modulus word size of gnu hash and its derivative */
4474         h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4475         h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4476
4477         /* Filter out the "definitely not in set" queries */
4478         if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4479                 return (ESRCH);
4480
4481         /* Locate hash chain and corresponding value element*/
4482         bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4483         if (bucket == 0)
4484                 return (ESRCH);
4485         hashval = &obj->chain_zero_gnu[bucket];
4486         do {
4487                 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4488                         symnum = hashval - obj->chain_zero_gnu;
4489                         if (matched_symbol(req, obj, &matchres, symnum)) {
4490                                 req->sym_out = matchres.sym_out;
4491                                 req->defobj_out = obj;
4492                                 return (0);
4493                         }
4494                 }
4495         } while ((*hashval++ & 1) == 0);
4496         if (matchres.vcount == 1) {
4497                 req->sym_out = matchres.vsymp;
4498                 req->defobj_out = obj;
4499                 return (0);
4500         }
4501         return (ESRCH);
4502 }
4503
4504 static void
4505 trace_loaded_objects(Obj_Entry *obj)
4506 {
4507     const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
4508     int c;
4509
4510     if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL)
4511         main_local = "";
4512
4513     if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL)
4514         fmt1 = "\t%o => %p (%x)\n";
4515
4516     if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL)
4517         fmt2 = "\t%o (%x)\n";
4518
4519     list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL"));
4520
4521     for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4522         Needed_Entry *needed;
4523         const char *name, *path;
4524         bool is_lib;
4525
4526         if (obj->marker)
4527             continue;
4528         if (list_containers && obj->needed != NULL)
4529             rtld_printf("%s:\n", obj->path);
4530         for (needed = obj->needed; needed; needed = needed->next) {
4531             if (needed->obj != NULL) {
4532                 if (needed->obj->traced && !list_containers)
4533                     continue;
4534                 needed->obj->traced = true;
4535                 path = needed->obj->path;
4536             } else
4537                 path = "not found";
4538
4539             name = obj->strtab + needed->name;
4540             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
4541
4542             fmt = is_lib ? fmt1 : fmt2;
4543             while ((c = *fmt++) != '\0') {
4544                 switch (c) {
4545                 default:
4546                     rtld_putchar(c);
4547                     continue;
4548                 case '\\':
4549                     switch (c = *fmt) {
4550                     case '\0':
4551                         continue;
4552                     case 'n':
4553                         rtld_putchar('\n');
4554                         break;
4555                     case 't':
4556                         rtld_putchar('\t');
4557                         break;
4558                     }
4559                     break;
4560                 case '%':
4561                     switch (c = *fmt) {
4562                     case '\0':
4563                         continue;
4564                     case '%':
4565                     default:
4566                         rtld_putchar(c);
4567                         break;
4568                     case 'A':
4569                         rtld_putstr(main_local);
4570                         break;
4571                     case 'a':
4572                         rtld_putstr(obj_main->path);
4573                         break;
4574                     case 'o':
4575                         rtld_putstr(name);
4576                         break;
4577 #if 0
4578                     case 'm':
4579                         rtld_printf("%d", sodp->sod_major);
4580                         break;
4581                     case 'n':
4582                         rtld_printf("%d", sodp->sod_minor);
4583                         break;
4584 #endif
4585                     case 'p':
4586                         rtld_putstr(path);
4587                         break;
4588                     case 'x':
4589                         rtld_printf("%p", needed->obj ? needed->obj->mapbase :
4590                           0);
4591                         break;
4592                     }
4593                     break;
4594                 }
4595                 ++fmt;
4596             }
4597         }
4598     }
4599 }
4600
4601 /*
4602  * Unload a dlopened object and its dependencies from memory and from
4603  * our data structures.  It is assumed that the DAG rooted in the
4604  * object has already been unreferenced, and that the object has a
4605  * reference count of 0.
4606  */
4607 static void
4608 unload_object(Obj_Entry *root, RtldLockState *lockstate)
4609 {
4610         Obj_Entry marker, *obj, *next;
4611
4612         assert(root->refcount == 0);
4613
4614         /*
4615          * Pass over the DAG removing unreferenced objects from
4616          * appropriate lists.
4617          */
4618         unlink_object(root);
4619
4620         /* Unmap all objects that are no longer referenced. */
4621         for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
4622                 next = TAILQ_NEXT(obj, next);
4623                 if (obj->marker || obj->refcount != 0)
4624                         continue;
4625                 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
4626                     obj->mapsize, 0, obj->path);
4627                 dbg("unloading \"%s\"", obj->path);
4628                 /*
4629                  * Unlink the object now to prevent new references from
4630                  * being acquired while the bind lock is dropped in
4631                  * recursive dlclose() invocations.
4632                  */
4633                 TAILQ_REMOVE(&obj_list, obj, next);
4634                 obj_count--;
4635
4636                 if (obj->filtees_loaded) {
4637                         if (next != NULL) {
4638                                 init_marker(&marker);
4639                                 TAILQ_INSERT_BEFORE(next, &marker, next);
4640                                 unload_filtees(obj, lockstate);
4641                                 next = TAILQ_NEXT(&marker, next);
4642                                 TAILQ_REMOVE(&obj_list, &marker, next);
4643                         } else
4644                                 unload_filtees(obj, lockstate);
4645                 }
4646                 release_object(obj);
4647         }
4648 }
4649
4650 static void
4651 unlink_object(Obj_Entry *root)
4652 {
4653     Objlist_Entry *elm;
4654
4655     if (root->refcount == 0) {
4656         /* Remove the object from the RTLD_GLOBAL list. */
4657         objlist_remove(&list_global, root);
4658
4659         /* Remove the object from all objects' DAG lists. */
4660         STAILQ_FOREACH(elm, &root->dagmembers, link) {
4661             objlist_remove(&elm->obj->dldags, root);
4662             if (elm->obj != root)
4663                 unlink_object(elm->obj);
4664         }
4665     }
4666 }
4667
4668 static void
4669 ref_dag(Obj_Entry *root)
4670 {
4671     Objlist_Entry *elm;
4672
4673     assert(root->dag_inited);
4674     STAILQ_FOREACH(elm, &root->dagmembers, link)
4675         elm->obj->refcount++;
4676 }
4677
4678 static void
4679 unref_dag(Obj_Entry *root)
4680 {
4681     Objlist_Entry *elm;
4682
4683     assert(root->dag_inited);
4684     STAILQ_FOREACH(elm, &root->dagmembers, link)
4685         elm->obj->refcount--;
4686 }
4687
4688 /*
4689  * Common code for MD __tls_get_addr().
4690  */
4691 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
4692 static void *
4693 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
4694 {
4695     Elf_Addr *newdtv, *dtv;
4696     RtldLockState lockstate;
4697     int to_copy;
4698
4699     dtv = *dtvp;
4700     /* Check dtv generation in case new modules have arrived */
4701     if (dtv[0] != tls_dtv_generation) {
4702         wlock_acquire(rtld_bind_lock, &lockstate);
4703         newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4704         to_copy = dtv[1];
4705         if (to_copy > tls_max_index)
4706             to_copy = tls_max_index;
4707         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
4708         newdtv[0] = tls_dtv_generation;
4709         newdtv[1] = tls_max_index;
4710         free(dtv);
4711         lock_release(rtld_bind_lock, &lockstate);
4712         dtv = *dtvp = newdtv;
4713     }
4714
4715     /* Dynamically allocate module TLS if necessary */
4716     if (dtv[index + 1] == 0) {
4717         /* Signal safe, wlock will block out signals. */
4718         wlock_acquire(rtld_bind_lock, &lockstate);
4719         if (!dtv[index + 1])
4720             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
4721         lock_release(rtld_bind_lock, &lockstate);
4722     }
4723     return ((void *)(dtv[index + 1] + offset));
4724 }
4725
4726 void *
4727 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
4728 {
4729         Elf_Addr *dtv;
4730
4731         dtv = *dtvp;
4732         /* Check dtv generation in case new modules have arrived */
4733         if (__predict_true(dtv[0] == tls_dtv_generation &&
4734             dtv[index + 1] != 0))
4735                 return ((void *)(dtv[index + 1] + offset));
4736         return (tls_get_addr_slow(dtvp, index, offset));
4737 }
4738
4739 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \
4740     defined(__powerpc__) || defined(__riscv)
4741
4742 /*
4743  * Return pointer to allocated TLS block
4744  */
4745 static void *
4746 get_tls_block_ptr(void *tcb, size_t tcbsize)
4747 {
4748     size_t extra_size, post_size, pre_size, tls_block_size;
4749     size_t tls_init_align;
4750
4751     tls_init_align = MAX(obj_main->tlsalign, 1);
4752
4753     /* Compute fragments sizes. */
4754     extra_size = tcbsize - TLS_TCB_SIZE;
4755     post_size = calculate_tls_post_size(tls_init_align);
4756     tls_block_size = tcbsize + post_size;
4757     pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4758
4759     return ((char *)tcb - pre_size - extra_size);
4760 }
4761
4762 /*
4763  * Allocate Static TLS using the Variant I method.
4764  *
4765  * For details on the layout, see lib/libc/gen/tls.c.
4766  *
4767  * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
4768  *     it is based on tls_last_offset, and TLS offsets here are really TCB
4769  *     offsets, whereas libc's tls_static_space is just the executable's static
4770  *     TLS segment.
4771  */
4772 void *
4773 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4774 {
4775     Obj_Entry *obj;
4776     char *tls_block;
4777     Elf_Addr *dtv, **tcb;
4778     Elf_Addr addr;
4779     Elf_Addr i;
4780     size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
4781     size_t tls_init_align;
4782
4783     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4784         return (oldtcb);
4785
4786     assert(tcbsize >= TLS_TCB_SIZE);
4787     maxalign = MAX(tcbalign, tls_static_max_align);
4788     tls_init_align = MAX(obj_main->tlsalign, 1);
4789
4790     /* Compute fragmets sizes. */
4791     extra_size = tcbsize - TLS_TCB_SIZE;
4792     post_size = calculate_tls_post_size(tls_init_align);
4793     tls_block_size = tcbsize + post_size;
4794     pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
4795     tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
4796
4797     /* Allocate whole TLS block */
4798     tls_block = malloc_aligned(tls_block_size, maxalign);
4799     tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
4800
4801     if (oldtcb != NULL) {
4802         memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
4803             tls_static_space);
4804         free_aligned(get_tls_block_ptr(oldtcb, tcbsize));
4805
4806         /* Adjust the DTV. */
4807         dtv = tcb[0];
4808         for (i = 0; i < dtv[1]; i++) {
4809             if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4810                 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4811                 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
4812             }
4813         }
4814     } else {
4815         dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4816         tcb[0] = dtv;
4817         dtv[0] = tls_dtv_generation;
4818         dtv[1] = tls_max_index;
4819
4820         for (obj = globallist_curr(objs); obj != NULL;
4821           obj = globallist_next(obj)) {
4822             if (obj->tlsoffset > 0) {
4823                 addr = (Elf_Addr)tcb + obj->tlsoffset;
4824                 if (obj->tlsinitsize > 0)
4825                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4826                 if (obj->tlssize > obj->tlsinitsize)
4827                     memset((void*)(addr + obj->tlsinitsize), 0,
4828                            obj->tlssize - obj->tlsinitsize);
4829                 dtv[obj->tlsindex + 1] = addr;
4830             }
4831         }
4832     }
4833
4834     return (tcb);
4835 }
4836
4837 void
4838 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
4839 {
4840     Elf_Addr *dtv;
4841     Elf_Addr tlsstart, tlsend;
4842     size_t post_size;
4843     size_t dtvsize, i, tls_init_align;
4844
4845     assert(tcbsize >= TLS_TCB_SIZE);
4846     tls_init_align = MAX(obj_main->tlsalign, 1);
4847
4848     /* Compute fragments sizes. */
4849     post_size = calculate_tls_post_size(tls_init_align);
4850
4851     tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
4852     tlsend = (Elf_Addr)tcb + tls_static_space;
4853
4854     dtv = *(Elf_Addr **)tcb;
4855     dtvsize = dtv[1];
4856     for (i = 0; i < dtvsize; i++) {
4857         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4858             free((void*)dtv[i+2]);
4859         }
4860     }
4861     free(dtv);
4862     free_aligned(get_tls_block_ptr(tcb, tcbsize));
4863 }
4864
4865 #endif
4866
4867 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__)
4868
4869 /*
4870  * Allocate Static TLS using the Variant II method.
4871  */
4872 void *
4873 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4874 {
4875     Obj_Entry *obj;
4876     size_t size, ralign;
4877     char *tls;
4878     Elf_Addr *dtv, *olddtv;
4879     Elf_Addr segbase, oldsegbase, addr;
4880     size_t i;
4881
4882     ralign = tcbalign;
4883     if (tls_static_max_align > ralign)
4884             ralign = tls_static_max_align;
4885     size = round(tls_static_space, ralign) + round(tcbsize, ralign);
4886
4887     assert(tcbsize >= 2*sizeof(Elf_Addr));
4888     tls = malloc_aligned(size, ralign);
4889     dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4890
4891     segbase = (Elf_Addr)(tls + round(tls_static_space, ralign));
4892     ((Elf_Addr*)segbase)[0] = segbase;
4893     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4894
4895     dtv[0] = tls_dtv_generation;
4896     dtv[1] = tls_max_index;
4897
4898     if (oldtls) {
4899         /*
4900          * Copy the static TLS block over whole.
4901          */
4902         oldsegbase = (Elf_Addr) oldtls;
4903         memcpy((void *)(segbase - tls_static_space),
4904                (const void *)(oldsegbase - tls_static_space),
4905                tls_static_space);
4906
4907         /*
4908          * If any dynamic TLS blocks have been created tls_get_addr(),
4909          * move them over.
4910          */
4911         olddtv = ((Elf_Addr**)oldsegbase)[1];
4912         for (i = 0; i < olddtv[1]; i++) {
4913             if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4914                 dtv[i+2] = olddtv[i+2];
4915                 olddtv[i+2] = 0;
4916             }
4917         }
4918
4919         /*
4920          * We assume that this block was the one we created with
4921          * allocate_initial_tls().
4922          */
4923         free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4924     } else {
4925         for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
4926                 if (obj->marker || obj->tlsoffset == 0)
4927                         continue;
4928                 addr = segbase - obj->tlsoffset;
4929                 memset((void*)(addr + obj->tlsinitsize),
4930                        0, obj->tlssize - obj->tlsinitsize);
4931                 if (obj->tlsinit) {
4932                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4933                     obj->static_tls_copied = true;
4934                 }
4935                 dtv[obj->tlsindex + 1] = addr;
4936         }
4937     }
4938
4939     return (void*) segbase;
4940 }
4941
4942 void
4943 free_tls(void *tls, size_t tcbsize  __unused, size_t tcbalign)
4944 {
4945     Elf_Addr* dtv;
4946     size_t size, ralign;
4947     int dtvsize, i;
4948     Elf_Addr tlsstart, tlsend;
4949
4950     /*
4951      * Figure out the size of the initial TLS block so that we can
4952      * find stuff which ___tls_get_addr() allocated dynamically.
4953      */
4954     ralign = tcbalign;
4955     if (tls_static_max_align > ralign)
4956             ralign = tls_static_max_align;
4957     size = round(tls_static_space, ralign);
4958
4959     dtv = ((Elf_Addr**)tls)[1];
4960     dtvsize = dtv[1];
4961     tlsend = (Elf_Addr) tls;
4962     tlsstart = tlsend - size;
4963     for (i = 0; i < dtvsize; i++) {
4964         if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) {
4965                 free_aligned((void *)dtv[i + 2]);
4966         }
4967     }
4968
4969     free_aligned((void *)tlsstart);
4970     free((void*) dtv);
4971 }
4972
4973 #endif
4974
4975 /*
4976  * Allocate TLS block for module with given index.
4977  */
4978 void *
4979 allocate_module_tls(int index)
4980 {
4981     Obj_Entry* obj;
4982     char* p;
4983
4984     TAILQ_FOREACH(obj, &obj_list, next) {
4985         if (obj->marker)
4986             continue;
4987         if (obj->tlsindex == index)
4988             break;
4989     }
4990     if (!obj) {
4991         _rtld_error("Can't find module with TLS index %d", index);
4992         rtld_die();
4993     }
4994
4995     p = malloc_aligned(obj->tlssize, obj->tlsalign);
4996     memcpy(p, obj->tlsinit, obj->tlsinitsize);
4997     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4998
4999     return p;
5000 }
5001
5002 bool
5003 allocate_tls_offset(Obj_Entry *obj)
5004 {
5005     size_t off;
5006
5007     if (obj->tls_done)
5008         return true;
5009
5010     if (obj->tlssize == 0) {
5011         obj->tls_done = true;
5012         return true;
5013     }
5014
5015     if (tls_last_offset == 0)
5016         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
5017     else
5018         off = calculate_tls_offset(tls_last_offset, tls_last_size,
5019                                    obj->tlssize, obj->tlsalign);
5020
5021     /*
5022      * If we have already fixed the size of the static TLS block, we
5023      * must stay within that size. When allocating the static TLS, we
5024      * leave a small amount of space spare to be used for dynamically
5025      * loading modules which use static TLS.
5026      */
5027     if (tls_static_space != 0) {
5028         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
5029             return false;
5030     } else if (obj->tlsalign > tls_static_max_align) {
5031             tls_static_max_align = obj->tlsalign;
5032     }
5033
5034     tls_last_offset = obj->tlsoffset = off;
5035     tls_last_size = obj->tlssize;
5036     obj->tls_done = true;
5037
5038     return true;
5039 }
5040
5041 void
5042 free_tls_offset(Obj_Entry *obj)
5043 {
5044
5045     /*
5046      * If we were the last thing to allocate out of the static TLS
5047      * block, we give our space back to the 'allocator'. This is a
5048      * simplistic workaround to allow libGL.so.1 to be loaded and
5049      * unloaded multiple times.
5050      */
5051     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
5052         == calculate_tls_end(tls_last_offset, tls_last_size)) {
5053         tls_last_offset -= obj->tlssize;
5054         tls_last_size = 0;
5055     }
5056 }
5057
5058 void *
5059 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5060 {
5061     void *ret;
5062     RtldLockState lockstate;
5063
5064     wlock_acquire(rtld_bind_lock, &lockstate);
5065     ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5066       tcbsize, tcbalign);
5067     lock_release(rtld_bind_lock, &lockstate);
5068     return (ret);
5069 }
5070
5071 void
5072 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5073 {
5074     RtldLockState lockstate;
5075
5076     wlock_acquire(rtld_bind_lock, &lockstate);
5077     free_tls(tcb, tcbsize, tcbalign);
5078     lock_release(rtld_bind_lock, &lockstate);
5079 }
5080
5081 static void
5082 object_add_name(Obj_Entry *obj, const char *name)
5083 {
5084     Name_Entry *entry;
5085     size_t len;
5086
5087     len = strlen(name);
5088     entry = malloc(sizeof(Name_Entry) + len);
5089
5090     if (entry != NULL) {
5091         strcpy(entry->name, name);
5092         STAILQ_INSERT_TAIL(&obj->names, entry, link);
5093     }
5094 }
5095
5096 static int
5097 object_match_name(const Obj_Entry *obj, const char *name)
5098 {
5099     Name_Entry *entry;
5100
5101     STAILQ_FOREACH(entry, &obj->names, link) {
5102         if (strcmp(name, entry->name) == 0)
5103             return (1);
5104     }
5105     return (0);
5106 }
5107
5108 static Obj_Entry *
5109 locate_dependency(const Obj_Entry *obj, const char *name)
5110 {
5111     const Objlist_Entry *entry;
5112     const Needed_Entry *needed;
5113
5114     STAILQ_FOREACH(entry, &list_main, link) {
5115         if (object_match_name(entry->obj, name))
5116             return entry->obj;
5117     }
5118
5119     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
5120         if (strcmp(obj->strtab + needed->name, name) == 0 ||
5121           (needed->obj != NULL && object_match_name(needed->obj, name))) {
5122             /*
5123              * If there is DT_NEEDED for the name we are looking for,
5124              * we are all set.  Note that object might not be found if
5125              * dependency was not loaded yet, so the function can
5126              * return NULL here.  This is expected and handled
5127              * properly by the caller.
5128              */
5129             return (needed->obj);
5130         }
5131     }
5132     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5133         obj->path, name);
5134     rtld_die();
5135 }
5136
5137 static int
5138 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5139     const Elf_Vernaux *vna)
5140 {
5141     const Elf_Verdef *vd;
5142     const char *vername;
5143
5144     vername = refobj->strtab + vna->vna_name;
5145     vd = depobj->verdef;
5146     if (vd == NULL) {
5147         _rtld_error("%s: version %s required by %s not defined",
5148             depobj->path, vername, refobj->path);
5149         return (-1);
5150     }
5151     for (;;) {
5152         if (vd->vd_version != VER_DEF_CURRENT) {
5153             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5154                 depobj->path, vd->vd_version);
5155             return (-1);
5156         }
5157         if (vna->vna_hash == vd->vd_hash) {
5158             const Elf_Verdaux *aux = (const Elf_Verdaux *)
5159                 ((const char *)vd + vd->vd_aux);
5160             if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5161                 return (0);
5162         }
5163         if (vd->vd_next == 0)
5164             break;
5165         vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5166     }
5167     if (vna->vna_flags & VER_FLG_WEAK)
5168         return (0);
5169     _rtld_error("%s: version %s required by %s not found",
5170         depobj->path, vername, refobj->path);
5171     return (-1);
5172 }
5173
5174 static int
5175 rtld_verify_object_versions(Obj_Entry *obj)
5176 {
5177     const Elf_Verneed *vn;
5178     const Elf_Verdef  *vd;
5179     const Elf_Verdaux *vda;
5180     const Elf_Vernaux *vna;
5181     const Obj_Entry *depobj;
5182     int maxvernum, vernum;
5183
5184     if (obj->ver_checked)
5185         return (0);
5186     obj->ver_checked = true;
5187
5188     maxvernum = 0;
5189     /*
5190      * Walk over defined and required version records and figure out
5191      * max index used by any of them. Do very basic sanity checking
5192      * while there.
5193      */
5194     vn = obj->verneed;
5195     while (vn != NULL) {
5196         if (vn->vn_version != VER_NEED_CURRENT) {
5197             _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5198                 obj->path, vn->vn_version);
5199             return (-1);
5200         }
5201         vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5202         for (;;) {
5203             vernum = VER_NEED_IDX(vna->vna_other);
5204             if (vernum > maxvernum)
5205                 maxvernum = vernum;
5206             if (vna->vna_next == 0)
5207                  break;
5208             vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5209         }
5210         if (vn->vn_next == 0)
5211             break;
5212         vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5213     }
5214
5215     vd = obj->verdef;
5216     while (vd != NULL) {
5217         if (vd->vd_version != VER_DEF_CURRENT) {
5218             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5219                 obj->path, vd->vd_version);
5220             return (-1);
5221         }
5222         vernum = VER_DEF_IDX(vd->vd_ndx);
5223         if (vernum > maxvernum)
5224                 maxvernum = vernum;
5225         if (vd->vd_next == 0)
5226             break;
5227         vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5228     }
5229
5230     if (maxvernum == 0)
5231         return (0);
5232
5233     /*
5234      * Store version information in array indexable by version index.
5235      * Verify that object version requirements are satisfied along the
5236      * way.
5237      */
5238     obj->vernum = maxvernum + 1;
5239     obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5240
5241     vd = obj->verdef;
5242     while (vd != NULL) {
5243         if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5244             vernum = VER_DEF_IDX(vd->vd_ndx);
5245             assert(vernum <= maxvernum);
5246             vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5247             obj->vertab[vernum].hash = vd->vd_hash;
5248             obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5249             obj->vertab[vernum].file = NULL;
5250             obj->vertab[vernum].flags = 0;
5251         }
5252         if (vd->vd_next == 0)
5253             break;
5254         vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5255     }
5256
5257     vn = obj->verneed;
5258     while (vn != NULL) {
5259         depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5260         if (depobj == NULL)
5261             return (-1);
5262         vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5263         for (;;) {
5264             if (check_object_provided_version(obj, depobj, vna))
5265                 return (-1);
5266             vernum = VER_NEED_IDX(vna->vna_other);
5267             assert(vernum <= maxvernum);
5268             obj->vertab[vernum].hash = vna->vna_hash;
5269             obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5270             obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5271             obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5272                 VER_INFO_HIDDEN : 0;
5273             if (vna->vna_next == 0)
5274                  break;
5275             vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5276         }
5277         if (vn->vn_next == 0)
5278             break;
5279         vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5280     }
5281     return 0;
5282 }
5283
5284 static int
5285 rtld_verify_versions(const Objlist *objlist)
5286 {
5287     Objlist_Entry *entry;
5288     int rc;
5289
5290     rc = 0;
5291     STAILQ_FOREACH(entry, objlist, link) {
5292         /*
5293          * Skip dummy objects or objects that have their version requirements
5294          * already checked.
5295          */
5296         if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5297             continue;
5298         if (rtld_verify_object_versions(entry->obj) == -1) {
5299             rc = -1;
5300             if (ld_tracing == NULL)
5301                 break;
5302         }
5303     }
5304     if (rc == 0 || ld_tracing != NULL)
5305         rc = rtld_verify_object_versions(&obj_rtld);
5306     return rc;
5307 }
5308
5309 const Ver_Entry *
5310 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5311 {
5312     Elf_Versym vernum;
5313
5314     if (obj->vertab) {
5315         vernum = VER_NDX(obj->versyms[symnum]);
5316         if (vernum >= obj->vernum) {
5317             _rtld_error("%s: symbol %s has wrong verneed value %d",
5318                 obj->path, obj->strtab + symnum, vernum);
5319         } else if (obj->vertab[vernum].hash != 0) {
5320             return &obj->vertab[vernum];
5321         }
5322     }
5323     return NULL;
5324 }
5325
5326 int
5327 _rtld_get_stack_prot(void)
5328 {
5329
5330         return (stack_prot);
5331 }
5332
5333 int
5334 _rtld_is_dlopened(void *arg)
5335 {
5336         Obj_Entry *obj;
5337         RtldLockState lockstate;
5338         int res;
5339
5340         rlock_acquire(rtld_bind_lock, &lockstate);
5341         obj = dlcheck(arg);
5342         if (obj == NULL)
5343                 obj = obj_from_addr(arg);
5344         if (obj == NULL) {
5345                 _rtld_error("No shared object contains address");
5346                 lock_release(rtld_bind_lock, &lockstate);
5347                 return (-1);
5348         }
5349         res = obj->dlopened ? 1 : 0;
5350         lock_release(rtld_bind_lock, &lockstate);
5351         return (res);
5352 }
5353
5354 static int
5355 obj_remap_relro(Obj_Entry *obj, int prot)
5356 {
5357
5358         if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5359             prot) == -1) {
5360                 _rtld_error("%s: Cannot set relro protection to %#x: %s",
5361                     obj->path, prot, rtld_strerror(errno));
5362                 return (-1);
5363         }
5364         return (0);
5365 }
5366
5367 static int
5368 obj_disable_relro(Obj_Entry *obj)
5369 {
5370
5371         return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5372 }
5373
5374 static int
5375 obj_enforce_relro(Obj_Entry *obj)
5376 {
5377
5378         return (obj_remap_relro(obj, PROT_READ));
5379 }
5380
5381 static void
5382 map_stacks_exec(RtldLockState *lockstate)
5383 {
5384         void (*thr_map_stacks_exec)(void);
5385
5386         if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5387                 return;
5388         thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5389             get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5390         if (thr_map_stacks_exec != NULL) {
5391                 stack_prot |= PROT_EXEC;
5392                 thr_map_stacks_exec();
5393         }
5394 }
5395
5396 static void
5397 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5398 {
5399         Objlist_Entry *elm;
5400         Obj_Entry *obj;
5401         void (*distrib)(size_t, void *, size_t, size_t);
5402
5403         distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5404             get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5405         if (distrib == NULL)
5406                 return;
5407         STAILQ_FOREACH(elm, list, link) {
5408                 obj = elm->obj;
5409                 if (obj->marker || !obj->tls_done || obj->static_tls_copied)
5410                         continue;
5411                 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5412                     obj->tlssize);
5413                 obj->static_tls_copied = true;
5414         }
5415 }
5416
5417 void
5418 symlook_init(SymLook *dst, const char *name)
5419 {
5420
5421         bzero(dst, sizeof(*dst));
5422         dst->name = name;
5423         dst->hash = elf_hash(name);
5424         dst->hash_gnu = gnu_hash(name);
5425 }
5426
5427 static void
5428 symlook_init_from_req(SymLook *dst, const SymLook *src)
5429 {
5430
5431         dst->name = src->name;
5432         dst->hash = src->hash;
5433         dst->hash_gnu = src->hash_gnu;
5434         dst->ventry = src->ventry;
5435         dst->flags = src->flags;
5436         dst->defobj_out = NULL;
5437         dst->sym_out = NULL;
5438         dst->lockstate = src->lockstate;
5439 }
5440
5441 static int
5442 open_binary_fd(const char *argv0, bool search_in_path)
5443 {
5444         char *pathenv, *pe, binpath[PATH_MAX];
5445         int fd;
5446
5447         if (search_in_path && strchr(argv0, '/') == NULL) {
5448                 pathenv = getenv("PATH");
5449                 if (pathenv == NULL) {
5450                         _rtld_error("-p and no PATH environment variable");
5451                         rtld_die();
5452                 }
5453                 pathenv = strdup(pathenv);
5454                 if (pathenv == NULL) {
5455                         _rtld_error("Cannot allocate memory");
5456                         rtld_die();
5457                 }
5458                 fd = -1;
5459                 errno = ENOENT;
5460                 while ((pe = strsep(&pathenv, ":")) != NULL) {
5461                         if (strlcpy(binpath, pe, sizeof(binpath)) >=
5462                             sizeof(binpath))
5463                                 continue;
5464                         if (binpath[0] != '\0' &&
5465                             strlcat(binpath, "/", sizeof(binpath)) >=
5466                             sizeof(binpath))
5467                                 continue;
5468                         if (strlcat(binpath, argv0, sizeof(binpath)) >=
5469                             sizeof(binpath))
5470                                 continue;
5471                         fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
5472                         if (fd != -1 || errno != ENOENT)
5473                                 break;
5474                 }
5475                 free(pathenv);
5476         } else {
5477                 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
5478         }
5479
5480         if (fd == -1) {
5481                 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
5482                 rtld_die();
5483         }
5484         return (fd);
5485 }
5486
5487 /*
5488  * Parse a set of command-line arguments.
5489  */
5490 static int
5491 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp)
5492 {
5493         const char *arg;
5494         int fd, i, j, arglen;
5495         char opt;
5496
5497         dbg("Parsing command-line arguments");
5498         *use_pathp = false;
5499         *fdp = -1;
5500
5501         for (i = 1; i < argc; i++ ) {
5502                 arg = argv[i];
5503                 dbg("argv[%d]: '%s'", i, arg);
5504
5505                 /*
5506                  * rtld arguments end with an explicit "--" or with the first
5507                  * non-prefixed argument.
5508                  */
5509                 if (strcmp(arg, "--") == 0) {
5510                         i++;
5511                         break;
5512                 }
5513                 if (arg[0] != '-')
5514                         break;
5515
5516                 /*
5517                  * All other arguments are single-character options that can
5518                  * be combined, so we need to search through `arg` for them.
5519                  */
5520                 arglen = strlen(arg);
5521                 for (j = 1; j < arglen; j++) {
5522                         opt = arg[j];
5523                         if (opt == 'h') {
5524                                 print_usage(argv[0]);
5525                                 _exit(0);
5526                         } else if (opt == 'f') {
5527                         /*
5528                          * -f XX can be used to specify a descriptor for the
5529                          * binary named at the command line (i.e., the later
5530                          * argument will specify the process name but the
5531                          * descriptor is what will actually be executed)
5532                          */
5533                         if (j != arglen - 1) {
5534                                 /* -f must be the last option in, e.g., -abcf */
5535                                 _rtld_error("Invalid options: %s", arg);
5536                                 rtld_die();
5537                         }
5538                         i++;
5539                         fd = parse_integer(argv[i]);
5540                         if (fd == -1) {
5541                                 _rtld_error("Invalid file descriptor: '%s'",
5542                                     argv[i]);
5543                                 rtld_die();
5544                         }
5545                         *fdp = fd;
5546                         break;
5547                         } else if (opt == 'p') {
5548                                 *use_pathp = true;
5549                         } else {
5550                                 _rtld_error("Invalid argument: '%s'", arg);
5551                                 print_usage(argv[0]);
5552                                 rtld_die();
5553                         }
5554                 }
5555         }
5556
5557         return (i);
5558 }
5559
5560 /*
5561  * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
5562  */
5563 static int
5564 parse_integer(const char *str)
5565 {
5566         static const int RADIX = 10;  /* XXXJA: possibly support hex? */
5567         const char *orig;
5568         int n;
5569         char c;
5570
5571         orig = str;
5572         n = 0;
5573         for (c = *str; c != '\0'; c = *++str) {
5574                 if (c < '0' || c > '9')
5575                         return (-1);
5576
5577                 n *= RADIX;
5578                 n += c - '0';
5579         }
5580
5581         /* Make sure we actually parsed something. */
5582         if (str == orig)
5583                 return (-1);
5584         return (n);
5585 }
5586
5587 static void
5588 print_usage(const char *argv0)
5589 {
5590
5591         rtld_printf("Usage: %s [-h] [-f <FD>] [--] <binary> [<args>]\n"
5592                 "\n"
5593                 "Options:\n"
5594                 "  -h        Display this help message\n"
5595                 "  -p        Search in PATH for named binary\n"
5596                 "  -f <FD>   Execute <FD> instead of searching for <binary>\n"
5597                 "  --        End of RTLD options\n"
5598                 "  <binary>  Name of process to execute\n"
5599                 "  <args>    Arguments to the executed process\n", argv0);
5600 }
5601
5602 /*
5603  * Overrides for libc_pic-provided functions.
5604  */
5605
5606 int
5607 __getosreldate(void)
5608 {
5609         size_t len;
5610         int oid[2];
5611         int error, osrel;
5612
5613         if (osreldate != 0)
5614                 return (osreldate);
5615
5616         oid[0] = CTL_KERN;
5617         oid[1] = KERN_OSRELDATE;
5618         osrel = 0;
5619         len = sizeof(osrel);
5620         error = sysctl(oid, 2, &osrel, &len, NULL, 0);
5621         if (error == 0 && osrel > 0 && len == sizeof(osrel))
5622                 osreldate = osrel;
5623         return (osreldate);
5624 }
5625
5626 void
5627 exit(int status)
5628 {
5629
5630         _exit(status);
5631 }
5632
5633 void (*__cleanup)(void);
5634 int __isthreaded = 0;
5635 int _thread_autoinit_dummy_decl = 1;
5636
5637 /*
5638  * No unresolved symbols for rtld.
5639  */
5640 void
5641 __pthread_cxa_finalize(struct dl_phdr_info *a __unused)
5642 {
5643 }
5644
5645 const char *
5646 rtld_strerror(int errnum)
5647 {
5648
5649         if (errnum < 0 || errnum >= sys_nerr)
5650                 return ("Unknown error");
5651         return (sys_errlist[errnum]);
5652 }
5653
5654 /*
5655  * No ifunc relocations.
5656  */
5657 void *
5658 memset(void *dest, int c, size_t len)
5659 {
5660         size_t i;
5661
5662         for (i = 0; i < len; i++)
5663                 ((char *)dest)[i] = c;
5664         return (dest);
5665 }
5666
5667 void
5668 bzero(void *dest, size_t len)
5669 {
5670         size_t i;
5671
5672         for (i = 0; i < len; i++)
5673                 ((char *)dest)[i] = 0;
5674 }
5675
5676 /* malloc */
5677 void *
5678 malloc(size_t nbytes)
5679 {
5680
5681         return (__crt_malloc(nbytes));
5682 }
5683
5684 void *
5685 calloc(size_t num, size_t size)
5686 {
5687
5688         return (__crt_calloc(num, size));
5689 }
5690
5691 void
5692 free(void *cp)
5693 {
5694
5695         __crt_free(cp);
5696 }
5697
5698 void *
5699 realloc(void *cp, size_t nbytes)
5700 {
5701
5702         return (__crt_realloc(cp, nbytes));
5703 }