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