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