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