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