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