xref: /freebsd/libexec/rtld-elf/rtld.c (revision 8a802df1de2d77fd0a62996bd785ca3f1326887f)
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 (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) ||
1733 		    note->n_descsz != sizeof(int32_t))
1734 			continue;
1735 		if (note->n_type != NT_FREEBSD_ABI_TAG &&
1736 		    note->n_type != NT_FREEBSD_FEATURE_CTL &&
1737 		    note->n_type != NT_FREEBSD_NOINIT_TAG)
1738 			continue;
1739 		note_name = (const char *)(note + 1);
1740 		if (strncmp(NOTE_FREEBSD_VENDOR, note_name,
1741 		    sizeof(NOTE_FREEBSD_VENDOR)) != 0)
1742 			continue;
1743 		switch (note->n_type) {
1744 		case NT_FREEBSD_ABI_TAG:
1745 			/* FreeBSD osrel note */
1746 			p = (uintptr_t)(note + 1);
1747 			p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1748 			obj->osrel = *(const int32_t *)(p);
1749 			dbg("note osrel %d", obj->osrel);
1750 			break;
1751 		case NT_FREEBSD_FEATURE_CTL:
1752 			/* FreeBSD ABI feature control note */
1753 			p = (uintptr_t)(note + 1);
1754 			p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
1755 			obj->fctl0 = *(const uint32_t *)(p);
1756 			dbg("note fctl0 %#x", obj->fctl0);
1757 			break;
1758 		case NT_FREEBSD_NOINIT_TAG:
1759 			/* FreeBSD 'crt does not call init' note */
1760 			obj->crt_no_init = true;
1761 			dbg("note crt_no_init");
1762 			break;
1763 		}
1764 	}
1765 }
1766 
1767 static Obj_Entry *
1768 dlcheck(void *handle)
1769 {
1770     Obj_Entry *obj;
1771 
1772     TAILQ_FOREACH(obj, &obj_list, next) {
1773 	if (obj == (Obj_Entry *) handle)
1774 	    break;
1775     }
1776 
1777     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1778 	_rtld_error("Invalid shared object handle %p", handle);
1779 	return (NULL);
1780     }
1781     return (obj);
1782 }
1783 
1784 /*
1785  * If the given object is already in the donelist, return true.  Otherwise
1786  * add the object to the list and return false.
1787  */
1788 static bool
1789 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1790 {
1791     unsigned int i;
1792 
1793     for (i = 0;  i < dlp->num_used;  i++)
1794 	if (dlp->objs[i] == obj)
1795 	    return (true);
1796     /*
1797      * Our donelist allocation should always be sufficient.  But if
1798      * our threads locking isn't working properly, more shared objects
1799      * could have been loaded since we allocated the list.  That should
1800      * never happen, but we'll handle it properly just in case it does.
1801      */
1802     if (dlp->num_used < dlp->num_alloc)
1803 	dlp->objs[dlp->num_used++] = obj;
1804     return (false);
1805 }
1806 
1807 /*
1808  * SysV hash function for symbol table lookup.  It is a slightly optimized
1809  * version of the hash specified by the System V ABI.
1810  */
1811 Elf32_Word
1812 elf_hash(const char *name)
1813 {
1814 	const unsigned char *p = (const unsigned char *)name;
1815 	Elf32_Word h = 0;
1816 
1817 	while (*p != '\0') {
1818 		h = (h << 4) + *p++;
1819 		h ^= (h >> 24) & 0xf0;
1820 	}
1821 	return (h & 0x0fffffff);
1822 }
1823 
1824 /*
1825  * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits
1826  * unsigned in case it's implemented with a wider type.
1827  */
1828 static uint32_t
1829 gnu_hash(const char *s)
1830 {
1831 	uint32_t h;
1832 	unsigned char c;
1833 
1834 	h = 5381;
1835 	for (c = *s; c != '\0'; c = *++s)
1836 		h = h * 33 + c;
1837 	return (h & 0xffffffff);
1838 }
1839 
1840 
1841 /*
1842  * Find the library with the given name, and return its full pathname.
1843  * The returned string is dynamically allocated.  Generates an error
1844  * message and returns NULL if the library cannot be found.
1845  *
1846  * If the second argument is non-NULL, then it refers to an already-
1847  * loaded shared object, whose library search path will be searched.
1848  *
1849  * If a library is successfully located via LD_LIBRARY_PATH_FDS, its
1850  * descriptor (which is close-on-exec) will be passed out via the third
1851  * argument.
1852  *
1853  * The search order is:
1854  *   DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1)
1855  *   DT_RPATH of the main object if DSO without defined DT_RUNPATH (1)
1856  *   LD_LIBRARY_PATH
1857  *   DT_RUNPATH in the referencing file
1858  *   ldconfig hints (if -z nodefaultlib, filter out default library directories
1859  *	 from list)
1860  *   /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib
1861  *
1862  * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined.
1863  */
1864 static char *
1865 find_library(const char *xname, const Obj_Entry *refobj, int *fdp)
1866 {
1867 	char *pathname, *refobj_path;
1868 	const char *name;
1869 	bool nodeflib, objgiven;
1870 
1871 	objgiven = refobj != NULL;
1872 
1873 	if (libmap_disable || !objgiven ||
1874 	    (name = lm_find(refobj->path, xname)) == NULL)
1875 		name = xname;
1876 
1877 	if (strchr(name, '/') != NULL) {	/* Hard coded pathname */
1878 		if (name[0] != '/' && !trust) {
1879 			_rtld_error("Absolute pathname required "
1880 			    "for shared object \"%s\"", name);
1881 			return (NULL);
1882 		}
1883 		return (origin_subst(__DECONST(Obj_Entry *, refobj),
1884 		    __DECONST(char *, name)));
1885 	}
1886 
1887 	dbg(" Searching for \"%s\"", name);
1888 	refobj_path = objgiven ? refobj->path : NULL;
1889 
1890 	/*
1891 	 * If refobj->rpath != NULL, then refobj->runpath is NULL.  Fall
1892 	 * back to pre-conforming behaviour if user requested so with
1893 	 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z
1894 	 * nodeflib.
1895 	 */
1896 	if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) {
1897 		pathname = search_library_path(name, ld_library_path,
1898 		    refobj_path, fdp);
1899 		if (pathname != NULL)
1900 			return (pathname);
1901 		if (refobj != NULL) {
1902 			pathname = search_library_path(name, refobj->rpath,
1903 			    refobj_path, fdp);
1904 			if (pathname != NULL)
1905 				return (pathname);
1906 		}
1907 		pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1908 		if (pathname != NULL)
1909 			return (pathname);
1910 		pathname = search_library_path(name, gethints(false),
1911 		    refobj_path, fdp);
1912 		if (pathname != NULL)
1913 			return (pathname);
1914 		pathname = search_library_path(name, ld_standard_library_path,
1915 		    refobj_path, fdp);
1916 		if (pathname != NULL)
1917 			return (pathname);
1918 	} else {
1919 		nodeflib = objgiven ? refobj->z_nodeflib : false;
1920 		if (objgiven) {
1921 			pathname = search_library_path(name, refobj->rpath,
1922 			    refobj->path, fdp);
1923 			if (pathname != NULL)
1924 				return (pathname);
1925 		}
1926 		if (objgiven && refobj->runpath == NULL && refobj != obj_main) {
1927 			pathname = search_library_path(name, obj_main->rpath,
1928 			    refobj_path, fdp);
1929 			if (pathname != NULL)
1930 				return (pathname);
1931 		}
1932 		pathname = search_library_path(name, ld_library_path,
1933 		    refobj_path, fdp);
1934 		if (pathname != NULL)
1935 			return (pathname);
1936 		if (objgiven) {
1937 			pathname = search_library_path(name, refobj->runpath,
1938 			    refobj_path, fdp);
1939 			if (pathname != NULL)
1940 				return (pathname);
1941 		}
1942 		pathname = search_library_pathfds(name, ld_library_dirs, fdp);
1943 		if (pathname != NULL)
1944 			return (pathname);
1945 		pathname = search_library_path(name, gethints(nodeflib),
1946 		    refobj_path, fdp);
1947 		if (pathname != NULL)
1948 			return (pathname);
1949 		if (objgiven && !nodeflib) {
1950 			pathname = search_library_path(name,
1951 			    ld_standard_library_path, refobj_path, fdp);
1952 			if (pathname != NULL)
1953 				return (pathname);
1954 		}
1955 	}
1956 
1957 	if (objgiven && refobj->path != NULL) {
1958 		_rtld_error("Shared object \"%s\" not found, "
1959 		    "required by \"%s\"", name, basename(refobj->path));
1960 	} else {
1961 		_rtld_error("Shared object \"%s\" not found", name);
1962 	}
1963 	return (NULL);
1964 }
1965 
1966 /*
1967  * Given a symbol number in a referencing object, find the corresponding
1968  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1969  * no definition was found.  Returns a pointer to the Obj_Entry of the
1970  * defining object via the reference parameter DEFOBJ_OUT.
1971  */
1972 const Elf_Sym *
1973 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1974     const Obj_Entry **defobj_out, int flags, SymCache *cache,
1975     RtldLockState *lockstate)
1976 {
1977     const Elf_Sym *ref;
1978     const Elf_Sym *def;
1979     const Obj_Entry *defobj;
1980     const Ver_Entry *ve;
1981     SymLook req;
1982     const char *name;
1983     int res;
1984 
1985     /*
1986      * If we have already found this symbol, get the information from
1987      * the cache.
1988      */
1989     if (symnum >= refobj->dynsymcount)
1990 	return (NULL);	/* Bad object */
1991     if (cache != NULL && cache[symnum].sym != NULL) {
1992 	*defobj_out = cache[symnum].obj;
1993 	return (cache[symnum].sym);
1994     }
1995 
1996     ref = refobj->symtab + symnum;
1997     name = refobj->strtab + ref->st_name;
1998     def = NULL;
1999     defobj = NULL;
2000     ve = NULL;
2001 
2002     /*
2003      * We don't have to do a full scale lookup if the symbol is local.
2004      * We know it will bind to the instance in this load module; to
2005      * which we already have a pointer (ie ref). By not doing a lookup,
2006      * we not only improve performance, but it also avoids unresolvable
2007      * symbols when local symbols are not in the hash table. This has
2008      * been seen with the ia64 toolchain.
2009      */
2010     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
2011 	if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
2012 	    _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
2013 		symnum);
2014 	}
2015 	symlook_init(&req, name);
2016 	req.flags = flags;
2017 	ve = req.ventry = fetch_ventry(refobj, symnum);
2018 	req.lockstate = lockstate;
2019 	res = symlook_default(&req, refobj);
2020 	if (res == 0) {
2021 	    def = req.sym_out;
2022 	    defobj = req.defobj_out;
2023 	}
2024     } else {
2025 	def = ref;
2026 	defobj = refobj;
2027     }
2028 
2029     /*
2030      * If we found no definition and the reference is weak, treat the
2031      * symbol as having the value zero.
2032      */
2033     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
2034 	def = &sym_zero;
2035 	defobj = obj_main;
2036     }
2037 
2038     if (def != NULL) {
2039 	*defobj_out = defobj;
2040 	/* Record the information in the cache to avoid subsequent lookups. */
2041 	if (cache != NULL) {
2042 	    cache[symnum].sym = def;
2043 	    cache[symnum].obj = defobj;
2044 	}
2045     } else {
2046 	if (refobj != &obj_rtld)
2047 	    _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name,
2048 	      ve != NULL ? "@" : "", ve != NULL ? ve->name : "");
2049     }
2050     return (def);
2051 }
2052 
2053 /* Convert between native byte order and forced little resp. big endian. */
2054 #define COND_SWAP(n) (is_le ? le32toh(n) : be32toh(n))
2055 
2056 /*
2057  * Return the search path from the ldconfig hints file, reading it if
2058  * necessary.  If nostdlib is true, then the default search paths are
2059  * not added to result.
2060  *
2061  * Returns NULL if there are problems with the hints file,
2062  * or if the search path there is empty.
2063  */
2064 static const char *
2065 gethints(bool nostdlib)
2066 {
2067 	static char *filtered_path;
2068 	static const char *hints;
2069 	static struct elfhints_hdr hdr;
2070 	struct fill_search_info_args sargs, hargs;
2071 	struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo;
2072 	struct dl_serpath *SLPpath, *hintpath;
2073 	char *p;
2074 	struct stat hint_stat;
2075 	unsigned int SLPndx, hintndx, fndx, fcount;
2076 	int fd;
2077 	size_t flen;
2078 	uint32_t dl;
2079 	uint32_t magic;		/* Magic number */
2080 	uint32_t version;	/* File version (1) */
2081 	uint32_t strtab;	/* Offset of string table in file */
2082 	uint32_t dirlist;	/* Offset of directory list in string table */
2083 	uint32_t dirlistlen;	/* strlen(dirlist) */
2084 	bool is_le;
2085 	bool skip;
2086 
2087 	/* First call, read the hints file */
2088 	if (hints == NULL) {
2089 		/* Keep from trying again in case the hints file is bad. */
2090 		hints = "";
2091 
2092 		if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1) {
2093 			dbg("failed to open hints file \"%s\"", ld_elf_hints_path);
2094 			return (NULL);
2095 		}
2096 
2097 		/*
2098 		 * Check of hdr.dirlistlen value against type limit
2099 		 * intends to pacify static analyzers.  Further
2100 		 * paranoia leads to checks that dirlist is fully
2101 		 * contained in the file range.
2102 		 */
2103 		if (read(fd, &hdr, sizeof hdr) != sizeof hdr) {
2104 			dbg("failed to read %lu bytes from hints file \"%s\"",
2105 			    (u_long)sizeof hdr, ld_elf_hints_path);
2106 cleanup1:
2107 			close(fd);
2108 			hdr.dirlistlen = 0;
2109 			return (NULL);
2110 		}
2111 		is_le = /*le32toh(1) == 1 || */ hdr.magic == ELFHINTS_MAGIC;
2112 		magic = COND_SWAP(hdr.magic);
2113 		version = COND_SWAP(hdr.version);
2114 		strtab = COND_SWAP(hdr.strtab);
2115 		dirlist = COND_SWAP(hdr.dirlist);
2116 		dirlistlen = COND_SWAP(hdr.dirlistlen);
2117 		if (magic != ELFHINTS_MAGIC) {
2118 			dbg("invalid magic number %#08x (expected: %#08x)",
2119 			    magic, ELFHINTS_MAGIC);
2120 			goto cleanup1;
2121 		}
2122 		if (version != 1) {
2123 			dbg("hints file version %d (expected: 1)", version);
2124 			goto cleanup1;
2125 		}
2126 		if (dirlistlen > UINT_MAX / 2) {
2127 			dbg("directory list is to long: %d > %d",
2128 			    dirlistlen, UINT_MAX / 2);
2129 			goto cleanup1;
2130 		}
2131 		if (fstat(fd, &hint_stat) == -1) {
2132 			dbg("failed to find length of hints file \"%s\"",
2133 			    ld_elf_hints_path);
2134 			goto cleanup1;
2135 		}
2136 		dl = strtab;
2137 		if (dl + dirlist < dl) {
2138 			dbg("invalid string table position %d", dl);
2139 			goto cleanup1;
2140 		}
2141 		dl += dirlist;
2142 		if (dl + dirlistlen < dl) {
2143 			dbg("invalid directory list offset %d", dirlist);
2144 			goto cleanup1;
2145 		}
2146 		dl += dirlistlen;
2147 		if (dl > hint_stat.st_size) {
2148 			dbg("hints file \"%s\" is truncated (%d vs. %jd bytes)",
2149 			    ld_elf_hints_path, dl, (uintmax_t)hint_stat.st_size);
2150 			goto cleanup1;
2151 		}
2152 		p = xmalloc(dirlistlen + 1);
2153 		if (pread(fd, p, dirlistlen + 1,
2154 		    strtab + dirlist) != (ssize_t)dirlistlen + 1 ||
2155 		    p[dirlistlen] != '\0') {
2156 			free(p);
2157 			dbg("failed to read %d bytes starting at %d from hints file \"%s\"",
2158 			    dirlistlen + 1, strtab + dirlist, ld_elf_hints_path);
2159 			goto cleanup1;
2160 		}
2161 		hints = p;
2162 		close(fd);
2163 	}
2164 
2165 	/*
2166 	 * If caller agreed to receive list which includes the default
2167 	 * paths, we are done. Otherwise, if we still did not
2168 	 * calculated filtered result, do it now.
2169 	 */
2170 	if (!nostdlib)
2171 		return (hints[0] != '\0' ? hints : NULL);
2172 	if (filtered_path != NULL)
2173 		goto filt_ret;
2174 
2175 	/*
2176 	 * Obtain the list of all configured search paths, and the
2177 	 * list of the default paths.
2178 	 *
2179 	 * First estimate the size of the results.
2180 	 */
2181 	smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2182 	smeta.dls_cnt = 0;
2183 	hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2184 	hmeta.dls_cnt = 0;
2185 
2186 	sargs.request = RTLD_DI_SERINFOSIZE;
2187 	sargs.serinfo = &smeta;
2188 	hargs.request = RTLD_DI_SERINFOSIZE;
2189 	hargs.serinfo = &hmeta;
2190 
2191 	path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2192 	    &sargs);
2193 	path_enumerate(hints, fill_search_info, NULL, &hargs);
2194 
2195 	SLPinfo = xmalloc(smeta.dls_size);
2196 	hintinfo = xmalloc(hmeta.dls_size);
2197 
2198 	/*
2199 	 * Next fetch both sets of paths.
2200 	 */
2201 	sargs.request = RTLD_DI_SERINFO;
2202 	sargs.serinfo = SLPinfo;
2203 	sargs.serpath = &SLPinfo->dls_serpath[0];
2204 	sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt];
2205 
2206 	hargs.request = RTLD_DI_SERINFO;
2207 	hargs.serinfo = hintinfo;
2208 	hargs.serpath = &hintinfo->dls_serpath[0];
2209 	hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt];
2210 
2211 	path_enumerate(ld_standard_library_path, fill_search_info, NULL,
2212 	    &sargs);
2213 	path_enumerate(hints, fill_search_info, NULL, &hargs);
2214 
2215 	/*
2216 	 * Now calculate the difference between two sets, by excluding
2217 	 * standard paths from the full set.
2218 	 */
2219 	fndx = 0;
2220 	fcount = 0;
2221 	filtered_path = xmalloc(dirlistlen + 1);
2222 	hintpath = &hintinfo->dls_serpath[0];
2223 	for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) {
2224 		skip = false;
2225 		SLPpath = &SLPinfo->dls_serpath[0];
2226 		/*
2227 		 * Check each standard path against current.
2228 		 */
2229 		for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) {
2230 			/* matched, skip the path */
2231 			if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) {
2232 				skip = true;
2233 				break;
2234 			}
2235 		}
2236 		if (skip)
2237 			continue;
2238 		/*
2239 		 * Not matched against any standard path, add the path
2240 		 * to result. Separate consequtive paths with ':'.
2241 		 */
2242 		if (fcount > 0) {
2243 			filtered_path[fndx] = ':';
2244 			fndx++;
2245 		}
2246 		fcount++;
2247 		flen = strlen(hintpath->dls_name);
2248 		strncpy((filtered_path + fndx),	hintpath->dls_name, flen);
2249 		fndx += flen;
2250 	}
2251 	filtered_path[fndx] = '\0';
2252 
2253 	free(SLPinfo);
2254 	free(hintinfo);
2255 
2256 filt_ret:
2257 	return (filtered_path[0] != '\0' ? filtered_path : NULL);
2258 }
2259 
2260 static void
2261 init_dag(Obj_Entry *root)
2262 {
2263     const Needed_Entry *needed;
2264     const Objlist_Entry *elm;
2265     DoneList donelist;
2266 
2267     if (root->dag_inited)
2268 	return;
2269     donelist_init(&donelist);
2270 
2271     /* Root object belongs to own DAG. */
2272     objlist_push_tail(&root->dldags, root);
2273     objlist_push_tail(&root->dagmembers, root);
2274     donelist_check(&donelist, root);
2275 
2276     /*
2277      * Add dependencies of root object to DAG in breadth order
2278      * by exploiting the fact that each new object get added
2279      * to the tail of the dagmembers list.
2280      */
2281     STAILQ_FOREACH(elm, &root->dagmembers, link) {
2282 	for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
2283 	    if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
2284 		continue;
2285 	    objlist_push_tail(&needed->obj->dldags, root);
2286 	    objlist_push_tail(&root->dagmembers, needed->obj);
2287 	}
2288     }
2289     root->dag_inited = true;
2290 }
2291 
2292 static void
2293 init_marker(Obj_Entry *marker)
2294 {
2295 
2296 	bzero(marker, sizeof(*marker));
2297 	marker->marker = true;
2298 }
2299 
2300 Obj_Entry *
2301 globallist_curr(const Obj_Entry *obj)
2302 {
2303 
2304 	for (;;) {
2305 		if (obj == NULL)
2306 			return (NULL);
2307 		if (!obj->marker)
2308 			return (__DECONST(Obj_Entry *, obj));
2309 		obj = TAILQ_PREV(obj, obj_entry_q, next);
2310 	}
2311 }
2312 
2313 Obj_Entry *
2314 globallist_next(const Obj_Entry *obj)
2315 {
2316 
2317 	for (;;) {
2318 		obj = TAILQ_NEXT(obj, next);
2319 		if (obj == NULL)
2320 			return (NULL);
2321 		if (!obj->marker)
2322 			return (__DECONST(Obj_Entry *, obj));
2323 	}
2324 }
2325 
2326 /* Prevent the object from being unmapped while the bind lock is dropped. */
2327 static void
2328 hold_object(Obj_Entry *obj)
2329 {
2330 
2331 	obj->holdcount++;
2332 }
2333 
2334 static void
2335 unhold_object(Obj_Entry *obj)
2336 {
2337 
2338 	assert(obj->holdcount > 0);
2339 	if (--obj->holdcount == 0 && obj->unholdfree)
2340 		release_object(obj);
2341 }
2342 
2343 static void
2344 process_z(Obj_Entry *root)
2345 {
2346 	const Objlist_Entry *elm;
2347 	Obj_Entry *obj;
2348 
2349 	/*
2350 	 * Walk over object DAG and process every dependent object
2351 	 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need
2352 	 * to grow their own DAG.
2353 	 *
2354 	 * For DF_1_GLOBAL, DAG is required for symbol lookups in
2355 	 * symlook_global() to work.
2356 	 *
2357 	 * For DF_1_NODELETE, the DAG should have its reference upped.
2358 	 */
2359 	STAILQ_FOREACH(elm, &root->dagmembers, link) {
2360 		obj = elm->obj;
2361 		if (obj == NULL)
2362 			continue;
2363 		if (obj->z_nodelete && !obj->ref_nodel) {
2364 			dbg("obj %s -z nodelete", obj->path);
2365 			init_dag(obj);
2366 			ref_dag(obj);
2367 			obj->ref_nodel = true;
2368 		}
2369 		if (obj->z_global && objlist_find(&list_global, obj) == NULL) {
2370 			dbg("obj %s -z global", obj->path);
2371 			objlist_push_tail(&list_global, obj);
2372 			init_dag(obj);
2373 		}
2374 	}
2375 }
2376 
2377 static void
2378 parse_rtld_phdr(Obj_Entry *obj)
2379 {
2380 	const Elf_Phdr *ph;
2381 	Elf_Addr note_start, note_end;
2382 
2383 	obj->stack_flags = PF_X | PF_R | PF_W;
2384 	for (ph = obj->phdr;  (const char *)ph < (const char *)obj->phdr +
2385 	    obj->phsize; ph++) {
2386 		switch (ph->p_type) {
2387 		case PT_GNU_STACK:
2388 			obj->stack_flags = ph->p_flags;
2389 			break;
2390 		case PT_GNU_RELRO:
2391 			obj->relro_page = obj->relocbase +
2392 			    rtld_trunc_page(ph->p_vaddr);
2393 			obj->relro_size = rtld_round_page(ph->p_memsz);
2394 			break;
2395 		case PT_NOTE:
2396 			note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr;
2397 			note_end = note_start + ph->p_filesz;
2398 			digest_notes(obj, note_start, note_end);
2399 			break;
2400 		}
2401 	}
2402 }
2403 
2404 /*
2405  * Initialize the dynamic linker.  The argument is the address at which
2406  * the dynamic linker has been mapped into memory.  The primary task of
2407  * this function is to relocate the dynamic linker.
2408  */
2409 static void
2410 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
2411 {
2412     Obj_Entry objtmp;	/* Temporary rtld object */
2413     const Elf_Ehdr *ehdr;
2414     const Elf_Dyn *dyn_rpath;
2415     const Elf_Dyn *dyn_soname;
2416     const Elf_Dyn *dyn_runpath;
2417 
2418 #ifdef RTLD_INIT_PAGESIZES_EARLY
2419     /* The page size is required by the dynamic memory allocator. */
2420     init_pagesizes(aux_info);
2421 #endif
2422 
2423     /*
2424      * Conjure up an Obj_Entry structure for the dynamic linker.
2425      *
2426      * The "path" member can't be initialized yet because string constants
2427      * cannot yet be accessed. Below we will set it correctly.
2428      */
2429     memset(&objtmp, 0, sizeof(objtmp));
2430     objtmp.path = NULL;
2431     objtmp.rtld = true;
2432     objtmp.mapbase = mapbase;
2433 #ifdef PIC
2434     objtmp.relocbase = mapbase;
2435 #endif
2436 
2437     objtmp.dynamic = rtld_dynamic(&objtmp);
2438     digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath);
2439     assert(objtmp.needed == NULL);
2440     assert(!objtmp.textrel);
2441     /*
2442      * Temporarily put the dynamic linker entry into the object list, so
2443      * that symbols can be found.
2444      */
2445     relocate_objects(&objtmp, true, &objtmp, 0, NULL);
2446 
2447     ehdr = (Elf_Ehdr *)mapbase;
2448     objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
2449     objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]);
2450 
2451     /* Initialize the object list. */
2452     TAILQ_INIT(&obj_list);
2453 
2454     /* Now that non-local variables can be accesses, copy out obj_rtld. */
2455     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
2456 
2457 #ifndef RTLD_INIT_PAGESIZES_EARLY
2458     /* The page size is required by the dynamic memory allocator. */
2459     init_pagesizes(aux_info);
2460 #endif
2461 
2462     if (aux_info[AT_OSRELDATE] != NULL)
2463 	    osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
2464 
2465     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath);
2466 
2467     /* Replace the path with a dynamically allocated copy. */
2468     obj_rtld.path = xstrdup(ld_path_rtld);
2469 
2470     parse_rtld_phdr(&obj_rtld);
2471     if (obj_enforce_relro(&obj_rtld) == -1)
2472 	rtld_die();
2473 
2474     r_debug.r_version = R_DEBUG_VERSION;
2475     r_debug.r_brk = r_debug_state;
2476     r_debug.r_state = RT_CONSISTENT;
2477     r_debug.r_ldbase = obj_rtld.relocbase;
2478 }
2479 
2480 /*
2481  * Retrieve the array of supported page sizes.  The kernel provides the page
2482  * sizes in increasing order.
2483  */
2484 static void
2485 init_pagesizes(Elf_Auxinfo **aux_info)
2486 {
2487 	static size_t psa[MAXPAGESIZES];
2488 	int mib[2];
2489 	size_t len, size;
2490 
2491 	if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] !=
2492 	    NULL) {
2493 		size = aux_info[AT_PAGESIZESLEN]->a_un.a_val;
2494 		pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr;
2495 	} else {
2496 		len = 2;
2497 		if (sysctlnametomib("hw.pagesizes", mib, &len) == 0)
2498 			size = sizeof(psa);
2499 		else {
2500 			/* As a fallback, retrieve the base page size. */
2501 			size = sizeof(psa[0]);
2502 			if (aux_info[AT_PAGESZ] != NULL) {
2503 				psa[0] = aux_info[AT_PAGESZ]->a_un.a_val;
2504 				goto psa_filled;
2505 			} else {
2506 				mib[0] = CTL_HW;
2507 				mib[1] = HW_PAGESIZE;
2508 				len = 2;
2509 			}
2510 		}
2511 		if (sysctl(mib, len, psa, &size, NULL, 0) == -1) {
2512 			_rtld_error("sysctl for hw.pagesize(s) failed");
2513 			rtld_die();
2514 		}
2515 psa_filled:
2516 		pagesizes = psa;
2517 	}
2518 	npagesizes = size / sizeof(pagesizes[0]);
2519 	/* Discard any invalid entries at the end of the array. */
2520 	while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0)
2521 		npagesizes--;
2522 
2523 	page_size = pagesizes[0];
2524 }
2525 
2526 /*
2527  * Add the init functions from a needed object list (and its recursive
2528  * needed objects) to "list".  This is not used directly; it is a helper
2529  * function for initlist_add_objects().  The write lock must be held
2530  * when this function is called.
2531  */
2532 static void
2533 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
2534 {
2535     /* Recursively process the successor needed objects. */
2536     if (needed->next != NULL)
2537 	initlist_add_neededs(needed->next, list);
2538 
2539     /* Process the current needed object. */
2540     if (needed->obj != NULL)
2541 	initlist_add_objects(needed->obj, needed->obj, list);
2542 }
2543 
2544 /*
2545  * Scan all of the DAGs rooted in the range of objects from "obj" to
2546  * "tail" and add their init functions to "list".  This recurses over
2547  * the DAGs and ensure the proper init ordering such that each object's
2548  * needed libraries are initialized before the object itself.  At the
2549  * same time, this function adds the objects to the global finalization
2550  * list "list_fini" in the opposite order.  The write lock must be
2551  * held when this function is called.
2552  */
2553 static void
2554 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list)
2555 {
2556     Obj_Entry *nobj;
2557 
2558     if (obj->init_scanned || obj->init_done)
2559 	return;
2560     obj->init_scanned = true;
2561 
2562     /* Recursively process the successor objects. */
2563     nobj = globallist_next(obj);
2564     if (nobj != NULL && obj != tail)
2565 	initlist_add_objects(nobj, tail, list);
2566 
2567     /* Recursively process the needed objects. */
2568     if (obj->needed != NULL)
2569 	initlist_add_neededs(obj->needed, list);
2570     if (obj->needed_filtees != NULL)
2571 	initlist_add_neededs(obj->needed_filtees, list);
2572     if (obj->needed_aux_filtees != NULL)
2573 	initlist_add_neededs(obj->needed_aux_filtees, list);
2574 
2575     /* Add the object to the init list. */
2576     objlist_push_tail(list, obj);
2577 
2578     /* Add the object to the global fini list in the reverse order. */
2579     if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
2580       && !obj->on_fini_list) {
2581 	objlist_push_head(&list_fini, obj);
2582 	obj->on_fini_list = true;
2583     }
2584 }
2585 
2586 static void
2587 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate)
2588 {
2589     Needed_Entry *needed, *needed1;
2590 
2591     for (needed = n; needed != NULL; needed = needed->next) {
2592 	if (needed->obj != NULL) {
2593 	    dlclose_locked(needed->obj, lockstate);
2594 	    needed->obj = NULL;
2595 	}
2596     }
2597     for (needed = n; needed != NULL; needed = needed1) {
2598 	needed1 = needed->next;
2599 	free(needed);
2600     }
2601 }
2602 
2603 static void
2604 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate)
2605 {
2606 
2607 	free_needed_filtees(obj->needed_filtees, lockstate);
2608 	obj->needed_filtees = NULL;
2609 	free_needed_filtees(obj->needed_aux_filtees, lockstate);
2610 	obj->needed_aux_filtees = NULL;
2611 	obj->filtees_loaded = false;
2612 }
2613 
2614 static void
2615 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
2616     RtldLockState *lockstate)
2617 {
2618 
2619     for (; needed != NULL; needed = needed->next) {
2620 	needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
2621 	  flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
2622 	  RTLD_LOCAL, lockstate);
2623     }
2624 }
2625 
2626 static void
2627 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
2628 {
2629 	if (obj->filtees_loaded || obj->filtees_loading)
2630 		return;
2631 	lock_restart_for_upgrade(lockstate);
2632 	obj->filtees_loading = true;
2633 	load_filtee1(obj, obj->needed_filtees, flags, lockstate);
2634 	load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
2635 	obj->filtees_loaded = true;
2636 	obj->filtees_loading = false;
2637 }
2638 
2639 static int
2640 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
2641 {
2642     Obj_Entry *obj1;
2643 
2644     for (; needed != NULL; needed = needed->next) {
2645 	obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
2646 	  flags & ~RTLD_LO_NOLOAD);
2647 	if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
2648 	    return (-1);
2649     }
2650     return (0);
2651 }
2652 
2653 /*
2654  * Given a shared object, traverse its list of needed objects, and load
2655  * each of them.  Returns 0 on success.  Generates an error message and
2656  * returns -1 on failure.
2657  */
2658 static int
2659 load_needed_objects(Obj_Entry *first, int flags)
2660 {
2661     Obj_Entry *obj;
2662 
2663     for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
2664 	if (obj->marker)
2665 	    continue;
2666 	if (process_needed(obj, obj->needed, flags) == -1)
2667 	    return (-1);
2668     }
2669     return (0);
2670 }
2671 
2672 static int
2673 load_preload_objects(const char *penv, bool isfd)
2674 {
2675 	Obj_Entry *obj;
2676 	const char *name;
2677 	size_t len;
2678 	char savech, *p, *psave;
2679 	int fd;
2680 	static const char delim[] = " \t:;";
2681 
2682 	if (penv == NULL)
2683 		return (0);
2684 
2685 	p = psave = xstrdup(penv);
2686 	p += strspn(p, delim);
2687 	while (*p != '\0') {
2688 		len = strcspn(p, delim);
2689 
2690 		savech = p[len];
2691 		p[len] = '\0';
2692 		if (isfd) {
2693 			name = NULL;
2694 			fd = parse_integer(p);
2695 			if (fd == -1) {
2696 				free(psave);
2697 				return (-1);
2698 			}
2699 		} else {
2700 			name = p;
2701 			fd = -1;
2702 		}
2703 
2704 		obj = load_object(name, fd, NULL, 0);
2705 		if (obj == NULL) {
2706 			free(psave);
2707 			return (-1);	/* XXX - cleanup */
2708 		}
2709 		obj->z_interpose = true;
2710 		p[len] = savech;
2711 		p += len;
2712 		p += strspn(p, delim);
2713 	}
2714 	LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
2715 
2716 	free(psave);
2717 	return (0);
2718 }
2719 
2720 static const char *
2721 printable_path(const char *path)
2722 {
2723 
2724 	return (path == NULL ? "<unknown>" : path);
2725 }
2726 
2727 /*
2728  * Load a shared object into memory, if it is not already loaded.  The
2729  * object may be specified by name or by user-supplied file descriptor
2730  * fd_u. In the later case, the fd_u descriptor is not closed, but its
2731  * duplicate is.
2732  *
2733  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
2734  * on failure.
2735  */
2736 static Obj_Entry *
2737 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
2738 {
2739     Obj_Entry *obj;
2740     int fd;
2741     struct stat sb;
2742     char *path;
2743 
2744     fd = -1;
2745     if (name != NULL) {
2746 	TAILQ_FOREACH(obj, &obj_list, next) {
2747 	    if (obj->marker || obj->doomed)
2748 		continue;
2749 	    if (object_match_name(obj, name))
2750 		return (obj);
2751 	}
2752 
2753 	path = find_library(name, refobj, &fd);
2754 	if (path == NULL)
2755 	    return (NULL);
2756     } else
2757 	path = NULL;
2758 
2759     if (fd >= 0) {
2760 	/*
2761 	 * search_library_pathfds() opens a fresh file descriptor for the
2762 	 * library, so there is no need to dup().
2763 	 */
2764     } else if (fd_u == -1) {
2765 	/*
2766 	 * If we didn't find a match by pathname, or the name is not
2767 	 * supplied, open the file and check again by device and inode.
2768 	 * This avoids false mismatches caused by multiple links or ".."
2769 	 * in pathnames.
2770 	 *
2771 	 * To avoid a race, we open the file and use fstat() rather than
2772 	 * using stat().
2773 	 */
2774 	if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) {
2775 	    _rtld_error("Cannot open \"%s\"", path);
2776 	    free(path);
2777 	    return (NULL);
2778 	}
2779     } else {
2780 	fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0);
2781 	if (fd == -1) {
2782 	    _rtld_error("Cannot dup fd");
2783 	    free(path);
2784 	    return (NULL);
2785 	}
2786     }
2787     if (fstat(fd, &sb) == -1) {
2788 	_rtld_error("Cannot fstat \"%s\"", printable_path(path));
2789 	close(fd);
2790 	free(path);
2791 	return (NULL);
2792     }
2793     TAILQ_FOREACH(obj, &obj_list, next) {
2794 	if (obj->marker || obj->doomed)
2795 	    continue;
2796 	if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
2797 	    break;
2798     }
2799     if (obj != NULL) {
2800 	if (name != NULL)
2801 	    object_add_name(obj, name);
2802 	free(path);
2803 	close(fd);
2804 	return (obj);
2805     }
2806     if (flags & RTLD_LO_NOLOAD) {
2807 	free(path);
2808 	close(fd);
2809 	return (NULL);
2810     }
2811 
2812     /* First use of this object, so we must map it in */
2813     obj = do_load_object(fd, name, path, &sb, flags);
2814     if (obj == NULL)
2815 	free(path);
2816     close(fd);
2817 
2818     return (obj);
2819 }
2820 
2821 static Obj_Entry *
2822 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
2823   int flags)
2824 {
2825     Obj_Entry *obj;
2826     struct statfs fs;
2827 
2828     /*
2829      * First, make sure that environment variables haven't been
2830      * used to circumvent the noexec flag on a filesystem.
2831      * We ignore fstatfs(2) failures, since fd might reference
2832      * not a file, e.g. shmfd.
2833      */
2834     if (dangerous_ld_env && fstatfs(fd, &fs) == 0 &&
2835 	(fs.f_flags & MNT_NOEXEC) != 0) {
2836 	    _rtld_error("Cannot execute objects on %s", fs.f_mntonname);
2837 	    return (NULL);
2838     }
2839 
2840     dbg("loading \"%s\"", printable_path(path));
2841     obj = map_object(fd, printable_path(path), sbp);
2842     if (obj == NULL)
2843         return (NULL);
2844 
2845     /*
2846      * If DT_SONAME is present in the object, digest_dynamic2 already
2847      * added it to the object names.
2848      */
2849     if (name != NULL)
2850 	object_add_name(obj, name);
2851     obj->path = path;
2852     if (!digest_dynamic(obj, 0))
2853 	goto errp;
2854     dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
2855 	obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
2856     if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) {
2857 	dbg("refusing to load PIE executable \"%s\"", obj->path);
2858 	_rtld_error("Cannot load PIE binary %s as DSO", obj->path);
2859 	goto errp;
2860     }
2861     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
2862       RTLD_LO_DLOPEN) {
2863 	dbg("refusing to load non-loadable \"%s\"", obj->path);
2864 	_rtld_error("Cannot dlopen non-loadable %s", obj->path);
2865 	goto errp;
2866     }
2867 
2868     obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0;
2869     TAILQ_INSERT_TAIL(&obj_list, obj, next);
2870     obj_count++;
2871     obj_loads++;
2872     linkmap_add(obj);	/* for GDB & dlinfo() */
2873     max_stack_flags |= obj->stack_flags;
2874 
2875     dbg("  %p .. %p: %s", obj->mapbase,
2876          obj->mapbase + obj->mapsize - 1, obj->path);
2877     if (obj->textrel)
2878 	dbg("  WARNING: %s has impure text", obj->path);
2879     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2880 	obj->path);
2881 
2882     return (obj);
2883 
2884 errp:
2885     munmap(obj->mapbase, obj->mapsize);
2886     obj_free(obj);
2887     return (NULL);
2888 }
2889 
2890 static int
2891 load_kpreload(const void *addr)
2892 {
2893 	Obj_Entry *obj;
2894 	const Elf_Ehdr *ehdr;
2895 	const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn;
2896 	static const char kname[] = "[vdso]";
2897 
2898 	ehdr = addr;
2899 	if (!check_elf_headers(ehdr, "kpreload"))
2900 		return (-1);
2901 	obj = obj_new();
2902 	phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff);
2903 	obj->phdr = phdr;
2904 	obj->phsize = ehdr->e_phnum * sizeof(*phdr);
2905 	phlimit = phdr + ehdr->e_phnum;
2906 	seg0 = segn = NULL;
2907 
2908 	for (; phdr < phlimit; phdr++) {
2909 		switch (phdr->p_type) {
2910 		case PT_DYNAMIC:
2911 			phdyn = phdr;
2912 			break;
2913 		case PT_GNU_STACK:
2914 			/* Absense of PT_GNU_STACK implies stack_flags == 0. */
2915 			obj->stack_flags = phdr->p_flags;
2916 			break;
2917 		case PT_LOAD:
2918 			if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr)
2919 				seg0 = phdr;
2920 			if (segn == NULL || segn->p_vaddr + segn->p_memsz <
2921 			    phdr->p_vaddr + phdr->p_memsz)
2922 				segn = phdr;
2923 			break;
2924 		}
2925 	}
2926 
2927 	obj->mapbase = __DECONST(caddr_t, addr);
2928 	obj->mapsize = segn->p_vaddr + segn->p_memsz - (Elf_Addr)addr;
2929 	obj->vaddrbase = 0;
2930 	obj->relocbase = obj->mapbase;
2931 
2932 	object_add_name(obj, kname);
2933 	obj->path = xstrdup(kname);
2934 	obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr);
2935 
2936 	if (!digest_dynamic(obj, 0)) {
2937 		obj_free(obj);
2938 		return (-1);
2939 	}
2940 
2941 	/*
2942 	 * We assume that kernel-preloaded object does not need
2943 	 * relocation.  It is currently written into read-only page,
2944 	 * handling relocations would mean we need to allocate at
2945 	 * least one additional page per AS.
2946 	 */
2947 	dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p",
2948 	    obj->path, obj->mapbase, obj->phdr, seg0,
2949 	    obj->relocbase + seg0->p_vaddr, obj->dynamic);
2950 
2951 	TAILQ_INSERT_TAIL(&obj_list, obj, next);
2952 	obj_count++;
2953 	obj_loads++;
2954 	linkmap_add(obj);	/* for GDB & dlinfo() */
2955 	max_stack_flags |= obj->stack_flags;
2956 
2957 	LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, 0, 0, obj->path);
2958 	return (0);
2959 }
2960 
2961 Obj_Entry *
2962 obj_from_addr(const void *addr)
2963 {
2964     Obj_Entry *obj;
2965 
2966     TAILQ_FOREACH(obj, &obj_list, next) {
2967 	if (obj->marker)
2968 	    continue;
2969 	if (addr < (void *) obj->mapbase)
2970 	    continue;
2971 	if (addr < (void *)(obj->mapbase + obj->mapsize))
2972 	    return obj;
2973     }
2974     return (NULL);
2975 }
2976 
2977 static void
2978 preinit_main(void)
2979 {
2980     Elf_Addr *preinit_addr;
2981     int index;
2982 
2983     preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2984     if (preinit_addr == NULL)
2985 	return;
2986 
2987     for (index = 0; index < obj_main->preinit_array_num; index++) {
2988 	if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2989 	    dbg("calling preinit function for %s at %p", obj_main->path,
2990 	      (void *)preinit_addr[index]);
2991 	    LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2992 	      0, 0, obj_main->path);
2993 	    call_init_pointer(obj_main, preinit_addr[index]);
2994 	}
2995     }
2996 }
2997 
2998 /*
2999  * Call the finalization functions for each of the objects in "list"
3000  * belonging to the DAG of "root" and referenced once. If NULL "root"
3001  * is specified, every finalization function will be called regardless
3002  * of the reference count and the list elements won't be freed. All of
3003  * the objects are expected to have non-NULL fini functions.
3004  */
3005 static void
3006 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
3007 {
3008     Objlist_Entry *elm;
3009     struct dlerror_save *saved_msg;
3010     Elf_Addr *fini_addr;
3011     int index;
3012 
3013     assert(root == NULL || root->refcount == 1);
3014 
3015     if (root != NULL)
3016 	root->doomed = true;
3017 
3018     /*
3019      * Preserve the current error message since a fini function might
3020      * call into the dynamic linker and overwrite it.
3021      */
3022     saved_msg = errmsg_save();
3023     do {
3024 	STAILQ_FOREACH(elm, list, link) {
3025 	    if (root != NULL && (elm->obj->refcount != 1 ||
3026 	      objlist_find(&root->dagmembers, elm->obj) == NULL))
3027 		continue;
3028 	    /* Remove object from fini list to prevent recursive invocation. */
3029 	    STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3030 	    /* Ensure that new references cannot be acquired. */
3031 	    elm->obj->doomed = true;
3032 
3033 	    hold_object(elm->obj);
3034 	    lock_release(rtld_bind_lock, lockstate);
3035 	    /*
3036 	     * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
3037 	     * When this happens, DT_FINI_ARRAY is processed first.
3038 	     */
3039 	    fini_addr = (Elf_Addr *)elm->obj->fini_array;
3040 	    if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
3041 		for (index = elm->obj->fini_array_num - 1; index >= 0;
3042 		  index--) {
3043 		    if (fini_addr[index] != 0 && fini_addr[index] != 1) {
3044 			dbg("calling fini function for %s at %p",
3045 			    elm->obj->path, (void *)fini_addr[index]);
3046 			LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
3047 			    (void *)fini_addr[index], 0, 0, elm->obj->path);
3048 			call_initfini_pointer(elm->obj, fini_addr[index]);
3049 		    }
3050 		}
3051 	    }
3052 	    if (elm->obj->fini != (Elf_Addr)NULL) {
3053 		dbg("calling fini function for %s at %p", elm->obj->path,
3054 		    (void *)elm->obj->fini);
3055 		LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
3056 		    0, 0, elm->obj->path);
3057 		call_initfini_pointer(elm->obj, elm->obj->fini);
3058 	    }
3059 	    wlock_acquire(rtld_bind_lock, lockstate);
3060 	    unhold_object(elm->obj);
3061 	    /* No need to free anything if process is going down. */
3062 	    if (root != NULL)
3063 	    	free(elm);
3064 	    /*
3065 	     * We must restart the list traversal after every fini call
3066 	     * because a dlclose() call from the fini function or from
3067 	     * another thread might have modified the reference counts.
3068 	     */
3069 	    break;
3070 	}
3071     } while (elm != NULL);
3072     errmsg_restore(saved_msg);
3073 }
3074 
3075 /*
3076  * Call the initialization functions for each of the objects in
3077  * "list".  All of the objects are expected to have non-NULL init
3078  * functions.
3079  */
3080 static void
3081 objlist_call_init(Objlist *list, RtldLockState *lockstate)
3082 {
3083     Objlist_Entry *elm;
3084     Obj_Entry *obj;
3085     struct dlerror_save *saved_msg;
3086     Elf_Addr *init_addr;
3087     void (*reg)(void (*)(void));
3088     int index;
3089 
3090     /*
3091      * Clean init_scanned flag so that objects can be rechecked and
3092      * possibly initialized earlier if any of vectors called below
3093      * cause the change by using dlopen.
3094      */
3095     TAILQ_FOREACH(obj, &obj_list, next) {
3096 	if (obj->marker)
3097 	    continue;
3098 	obj->init_scanned = false;
3099     }
3100 
3101     /*
3102      * Preserve the current error message since an init function might
3103      * call into the dynamic linker and overwrite it.
3104      */
3105     saved_msg = errmsg_save();
3106     STAILQ_FOREACH(elm, list, link) {
3107 	if (elm->obj->init_done) /* Initialized early. */
3108 	    continue;
3109 	/*
3110 	 * Race: other thread might try to use this object before current
3111 	 * one completes the initialization. Not much can be done here
3112 	 * without better locking.
3113 	 */
3114 	elm->obj->init_done = true;
3115 	hold_object(elm->obj);
3116 	reg = NULL;
3117 	if (elm->obj == obj_main && obj_main->crt_no_init) {
3118 		reg = (void (*)(void (*)(void)))get_program_var_addr(
3119 		    "__libc_atexit", lockstate);
3120 	}
3121 	lock_release(rtld_bind_lock, lockstate);
3122 	if (reg != NULL) {
3123 		reg(rtld_exit);
3124 		rtld_exit_ptr = rtld_nop_exit;
3125 	}
3126 
3127         /*
3128          * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
3129          * When this happens, DT_INIT is processed first.
3130          */
3131 	if (elm->obj->init != (Elf_Addr)NULL) {
3132 	    dbg("calling init function for %s at %p", elm->obj->path,
3133 	        (void *)elm->obj->init);
3134 	    LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
3135 	        0, 0, elm->obj->path);
3136 	    call_init_pointer(elm->obj, elm->obj->init);
3137 	}
3138 	init_addr = (Elf_Addr *)elm->obj->init_array;
3139 	if (init_addr != NULL) {
3140 	    for (index = 0; index < elm->obj->init_array_num; index++) {
3141 		if (init_addr[index] != 0 && init_addr[index] != 1) {
3142 		    dbg("calling init function for %s at %p", elm->obj->path,
3143 			(void *)init_addr[index]);
3144 		    LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
3145 			(void *)init_addr[index], 0, 0, elm->obj->path);
3146 		    call_init_pointer(elm->obj, init_addr[index]);
3147 		}
3148 	    }
3149 	}
3150 	wlock_acquire(rtld_bind_lock, lockstate);
3151 	unhold_object(elm->obj);
3152     }
3153     errmsg_restore(saved_msg);
3154 }
3155 
3156 static void
3157 objlist_clear(Objlist *list)
3158 {
3159     Objlist_Entry *elm;
3160 
3161     while (!STAILQ_EMPTY(list)) {
3162 	elm = STAILQ_FIRST(list);
3163 	STAILQ_REMOVE_HEAD(list, link);
3164 	free(elm);
3165     }
3166 }
3167 
3168 static Objlist_Entry *
3169 objlist_find(Objlist *list, const Obj_Entry *obj)
3170 {
3171     Objlist_Entry *elm;
3172 
3173     STAILQ_FOREACH(elm, list, link)
3174 	if (elm->obj == obj)
3175 	    return elm;
3176     return (NULL);
3177 }
3178 
3179 static void
3180 objlist_init(Objlist *list)
3181 {
3182     STAILQ_INIT(list);
3183 }
3184 
3185 static void
3186 objlist_push_head(Objlist *list, Obj_Entry *obj)
3187 {
3188     Objlist_Entry *elm;
3189 
3190     elm = NEW(Objlist_Entry);
3191     elm->obj = obj;
3192     STAILQ_INSERT_HEAD(list, elm, link);
3193 }
3194 
3195 static void
3196 objlist_push_tail(Objlist *list, Obj_Entry *obj)
3197 {
3198     Objlist_Entry *elm;
3199 
3200     elm = NEW(Objlist_Entry);
3201     elm->obj = obj;
3202     STAILQ_INSERT_TAIL(list, elm, link);
3203 }
3204 
3205 static void
3206 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj)
3207 {
3208 	Objlist_Entry *elm, *listelm;
3209 
3210 	STAILQ_FOREACH(listelm, list, link) {
3211 		if (listelm->obj == listobj)
3212 			break;
3213 	}
3214 	elm = NEW(Objlist_Entry);
3215 	elm->obj = obj;
3216 	if (listelm != NULL)
3217 		STAILQ_INSERT_AFTER(list, listelm, elm, link);
3218 	else
3219 		STAILQ_INSERT_TAIL(list, elm, link);
3220 }
3221 
3222 static void
3223 objlist_remove(Objlist *list, Obj_Entry *obj)
3224 {
3225     Objlist_Entry *elm;
3226 
3227     if ((elm = objlist_find(list, obj)) != NULL) {
3228 	STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
3229 	free(elm);
3230     }
3231 }
3232 
3233 /*
3234  * Relocate dag rooted in the specified object.
3235  * Returns 0 on success, or -1 on failure.
3236  */
3237 
3238 static int
3239 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
3240     int flags, RtldLockState *lockstate)
3241 {
3242 	Objlist_Entry *elm;
3243 	int error;
3244 
3245 	error = 0;
3246 	STAILQ_FOREACH(elm, &root->dagmembers, link) {
3247 		error = relocate_object(elm->obj, bind_now, rtldobj, flags,
3248 		    lockstate);
3249 		if (error == -1)
3250 			break;
3251 	}
3252 	return (error);
3253 }
3254 
3255 /*
3256  * Prepare for, or clean after, relocating an object marked with
3257  * DT_TEXTREL or DF_TEXTREL.  Before relocating, all read-only
3258  * segments are remapped read-write.  After relocations are done, the
3259  * segment's permissions are returned back to the modes specified in
3260  * the phdrs.  If any relocation happened, or always for wired
3261  * program, COW is triggered.
3262  */
3263 static int
3264 reloc_textrel_prot(Obj_Entry *obj, bool before)
3265 {
3266 	const Elf_Phdr *ph;
3267 	void *base;
3268 	size_t l, sz;
3269 	int prot;
3270 
3271 	for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0;
3272 	    l--, ph++) {
3273 		if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0)
3274 			continue;
3275 		base = obj->relocbase + rtld_trunc_page(ph->p_vaddr);
3276 		sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) -
3277 		    rtld_trunc_page(ph->p_vaddr);
3278 		prot = before ? (PROT_READ | PROT_WRITE) :
3279 		    convert_prot(ph->p_flags);
3280 		if (mprotect(base, sz, prot) == -1) {
3281 			_rtld_error("%s: Cannot write-%sable text segment: %s",
3282 			    obj->path, before ? "en" : "dis",
3283 			    rtld_strerror(errno));
3284 			return (-1);
3285 		}
3286 	}
3287 	return (0);
3288 }
3289 
3290 /* Process RELR relative relocations. */
3291 static void
3292 reloc_relr(Obj_Entry *obj)
3293 {
3294 	const Elf_Relr *relr, *relrlim;
3295 	Elf_Addr *where;
3296 
3297 	relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize);
3298 	for (relr = obj->relr; relr < relrlim; relr++) {
3299 	    Elf_Relr entry = *relr;
3300 
3301 	    if ((entry & 1) == 0) {
3302 		where = (Elf_Addr *)(obj->relocbase + entry);
3303 		*where++ += (Elf_Addr)obj->relocbase;
3304 	    } else {
3305 		for (long i = 0; (entry >>= 1) != 0; i++)
3306 		    if ((entry & 1) != 0)
3307 			where[i] += (Elf_Addr)obj->relocbase;
3308 		where += CHAR_BIT * sizeof(Elf_Relr) - 1;
3309 	    }
3310 	}
3311 }
3312 
3313 /*
3314  * Relocate single object.
3315  * Returns 0 on success, or -1 on failure.
3316  */
3317 static int
3318 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
3319     int flags, RtldLockState *lockstate)
3320 {
3321 
3322 	if (obj->relocated)
3323 		return (0);
3324 	obj->relocated = true;
3325 	if (obj != rtldobj)
3326 		dbg("relocating \"%s\"", obj->path);
3327 
3328 	if (obj->symtab == NULL || obj->strtab == NULL ||
3329 	    !(obj->valid_hash_sysv || obj->valid_hash_gnu))
3330 		dbg("object %s has no run-time symbol table", obj->path);
3331 
3332 	/* There are relocations to the write-protected text segment. */
3333 	if (obj->textrel && reloc_textrel_prot(obj, true) != 0)
3334 		return (-1);
3335 
3336 	/* Process the non-PLT non-IFUNC relocations. */
3337 	if (reloc_non_plt(obj, rtldobj, flags, lockstate))
3338 		return (-1);
3339 	reloc_relr(obj);
3340 
3341 	/* Re-protected the text segment. */
3342 	if (obj->textrel && reloc_textrel_prot(obj, false) != 0)
3343 		return (-1);
3344 
3345 	/* Set the special PLT or GOT entries. */
3346 	init_pltgot(obj);
3347 
3348 	/* Process the PLT relocations. */
3349 	if (reloc_plt(obj, flags, lockstate) == -1)
3350 		return (-1);
3351 	/* Relocate the jump slots if we are doing immediate binding. */
3352 	if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags,
3353 	    lockstate) == -1)
3354 		return (-1);
3355 
3356 	if (!obj->mainprog && obj_enforce_relro(obj) == -1)
3357 		return (-1);
3358 
3359 	/*
3360 	 * Set up the magic number and version in the Obj_Entry.  These
3361 	 * were checked in the crt1.o from the original ElfKit, so we
3362 	 * set them for backward compatibility.
3363 	 */
3364 	obj->magic = RTLD_MAGIC;
3365 	obj->version = RTLD_VERSION;
3366 
3367 	return (0);
3368 }
3369 
3370 /*
3371  * Relocate newly-loaded shared objects.  The argument is a pointer to
3372  * the Obj_Entry for the first such object.  All objects from the first
3373  * to the end of the list of objects are relocated.  Returns 0 on success,
3374  * or -1 on failure.
3375  */
3376 static int
3377 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
3378     int flags, RtldLockState *lockstate)
3379 {
3380 	Obj_Entry *obj;
3381 	int error;
3382 
3383 	for (error = 0, obj = first;  obj != NULL;
3384 	    obj = TAILQ_NEXT(obj, next)) {
3385 		if (obj->marker)
3386 			continue;
3387 		error = relocate_object(obj, bind_now, rtldobj, flags,
3388 		    lockstate);
3389 		if (error == -1)
3390 			break;
3391 	}
3392 	return (error);
3393 }
3394 
3395 /*
3396  * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
3397  * referencing STT_GNU_IFUNC symbols is postponed till the other
3398  * relocations are done.  The indirect functions specified as
3399  * ifunc are allowed to call other symbols, so we need to have
3400  * objects relocated before asking for resolution from indirects.
3401  *
3402  * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
3403  * instead of the usual lazy handling of PLT slots.  It is
3404  * consistent with how GNU does it.
3405  */
3406 static int
3407 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
3408     RtldLockState *lockstate)
3409 {
3410 
3411 	if (obj->ifuncs_resolved)
3412 		return (0);
3413 	obj->ifuncs_resolved = true;
3414 	if (!obj->irelative && !obj->irelative_nonplt &&
3415 	    !((obj->bind_now || bind_now) && obj->gnu_ifunc) &&
3416 	    !obj->non_plt_gnu_ifunc)
3417 		return (0);
3418 	if (obj_disable_relro(obj) == -1 ||
3419 	    (obj->irelative && reloc_iresolve(obj, lockstate) == -1) ||
3420 	    (obj->irelative_nonplt && reloc_iresolve_nonplt(obj,
3421 	    lockstate) == -1) ||
3422 	    ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
3423 	    reloc_gnu_ifunc(obj, flags, lockstate) == -1) ||
3424 	    (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld,
3425 	    flags | SYMLOOK_IFUNC, lockstate) == -1) ||
3426 	    obj_enforce_relro(obj) == -1)
3427 		return (-1);
3428 	return (0);
3429 }
3430 
3431 static int
3432 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
3433     RtldLockState *lockstate)
3434 {
3435 	Objlist_Entry *elm;
3436 	Obj_Entry *obj;
3437 
3438 	STAILQ_FOREACH(elm, list, link) {
3439 		obj = elm->obj;
3440 		if (obj->marker)
3441 			continue;
3442 		if (resolve_object_ifunc(obj, bind_now, flags,
3443 		    lockstate) == -1)
3444 			return (-1);
3445 	}
3446 	return (0);
3447 }
3448 
3449 /*
3450  * Cleanup procedure.  It will be called (by the atexit mechanism) just
3451  * before the process exits.
3452  */
3453 static void
3454 rtld_exit(void)
3455 {
3456     RtldLockState lockstate;
3457 
3458     wlock_acquire(rtld_bind_lock, &lockstate);
3459     dbg("rtld_exit()");
3460     objlist_call_fini(&list_fini, NULL, &lockstate);
3461     /* No need to remove the items from the list, since we are exiting. */
3462     if (!libmap_disable)
3463         lm_fini();
3464     lock_release(rtld_bind_lock, &lockstate);
3465 }
3466 
3467 static void
3468 rtld_nop_exit(void)
3469 {
3470 }
3471 
3472 /*
3473  * Iterate over a search path, translate each element, and invoke the
3474  * callback on the result.
3475  */
3476 static void *
3477 path_enumerate(const char *path, path_enum_proc callback,
3478     const char *refobj_path, void *arg)
3479 {
3480     const char *trans;
3481     if (path == NULL)
3482 	return (NULL);
3483 
3484     path += strspn(path, ":;");
3485     while (*path != '\0') {
3486 	size_t len;
3487 	char  *res;
3488 
3489 	len = strcspn(path, ":;");
3490 	trans = lm_findn(refobj_path, path, len);
3491 	if (trans)
3492 	    res = callback(trans, strlen(trans), arg);
3493 	else
3494 	    res = callback(path, len, arg);
3495 
3496 	if (res != NULL)
3497 	    return (res);
3498 
3499 	path += len;
3500 	path += strspn(path, ":;");
3501     }
3502 
3503     return (NULL);
3504 }
3505 
3506 struct try_library_args {
3507     const char	*name;
3508     size_t	 namelen;
3509     char	*buffer;
3510     size_t	 buflen;
3511     int		 fd;
3512 };
3513 
3514 static void *
3515 try_library_path(const char *dir, size_t dirlen, void *param)
3516 {
3517     struct try_library_args *arg;
3518     int fd;
3519 
3520     arg = param;
3521     if (*dir == '/' || trust) {
3522 	char *pathname;
3523 
3524 	if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
3525 		return (NULL);
3526 
3527 	pathname = arg->buffer;
3528 	strncpy(pathname, dir, dirlen);
3529 	pathname[dirlen] = '/';
3530 	strcpy(pathname + dirlen + 1, arg->name);
3531 
3532 	dbg("  Trying \"%s\"", pathname);
3533 	fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY);
3534 	if (fd >= 0) {
3535 	    dbg("  Opened \"%s\", fd %d", pathname, fd);
3536 	    pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
3537 	    strcpy(pathname, arg->buffer);
3538 	    arg->fd = fd;
3539 	    return (pathname);
3540 	} else {
3541 	    dbg("  Failed to open \"%s\": %s",
3542 		pathname, rtld_strerror(errno));
3543 	}
3544     }
3545     return (NULL);
3546 }
3547 
3548 static char *
3549 search_library_path(const char *name, const char *path,
3550     const char *refobj_path, int *fdp)
3551 {
3552     char *p;
3553     struct try_library_args arg;
3554 
3555     if (path == NULL)
3556 	return (NULL);
3557 
3558     arg.name = name;
3559     arg.namelen = strlen(name);
3560     arg.buffer = xmalloc(PATH_MAX);
3561     arg.buflen = PATH_MAX;
3562     arg.fd = -1;
3563 
3564     p = path_enumerate(path, try_library_path, refobj_path, &arg);
3565     *fdp = arg.fd;
3566 
3567     free(arg.buffer);
3568 
3569     return (p);
3570 }
3571 
3572 
3573 /*
3574  * Finds the library with the given name using the directory descriptors
3575  * listed in the LD_LIBRARY_PATH_FDS environment variable.
3576  *
3577  * Returns a freshly-opened close-on-exec file descriptor for the library,
3578  * or -1 if the library cannot be found.
3579  */
3580 static char *
3581 search_library_pathfds(const char *name, const char *path, int *fdp)
3582 {
3583 	char *envcopy, *fdstr, *found, *last_token;
3584 	size_t len;
3585 	int dirfd, fd;
3586 
3587 	dbg("%s('%s', '%s', fdp)", __func__, name, path);
3588 
3589 	/* Don't load from user-specified libdirs into setuid binaries. */
3590 	if (!trust)
3591 		return (NULL);
3592 
3593 	/* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */
3594 	if (path == NULL)
3595 		return (NULL);
3596 
3597 	/* LD_LIBRARY_PATH_FDS only works with relative paths. */
3598 	if (name[0] == '/') {
3599 		dbg("Absolute path (%s) passed to %s", name, __func__);
3600 		return (NULL);
3601 	}
3602 
3603 	/*
3604 	 * Use strtok_r() to walk the FD:FD:FD list.  This requires a local
3605 	 * copy of the path, as strtok_r rewrites separator tokens
3606 	 * with '\0'.
3607 	 */
3608 	found = NULL;
3609 	envcopy = xstrdup(path);
3610 	for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL;
3611 	    fdstr = strtok_r(NULL, ":", &last_token)) {
3612 		dirfd = parse_integer(fdstr);
3613 		if (dirfd < 0) {
3614 			_rtld_error("failed to parse directory FD: '%s'",
3615 				fdstr);
3616 			break;
3617 		}
3618 		fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY);
3619 		if (fd >= 0) {
3620 			*fdp = fd;
3621 			len = strlen(fdstr) + strlen(name) + 3;
3622 			found = xmalloc(len);
3623 			if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) {
3624 				_rtld_error("error generating '%d/%s'",
3625 				    dirfd, name);
3626 				rtld_die();
3627 			}
3628 			dbg("open('%s') => %d", found, fd);
3629 			break;
3630 		}
3631 	}
3632 	free(envcopy);
3633 
3634 	return (found);
3635 }
3636 
3637 
3638 int
3639 dlclose(void *handle)
3640 {
3641 	RtldLockState lockstate;
3642 	int error;
3643 
3644 	wlock_acquire(rtld_bind_lock, &lockstate);
3645 	error = dlclose_locked(handle, &lockstate);
3646 	lock_release(rtld_bind_lock, &lockstate);
3647 	return (error);
3648 }
3649 
3650 static int
3651 dlclose_locked(void *handle, RtldLockState *lockstate)
3652 {
3653     Obj_Entry *root;
3654 
3655     root = dlcheck(handle);
3656     if (root == NULL)
3657 	return (-1);
3658     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
3659 	root->path);
3660 
3661     /* Unreference the object and its dependencies. */
3662     root->dl_refcount--;
3663 
3664     if (root->refcount == 1) {
3665 	/*
3666 	 * The object will be no longer referenced, so we must unload it.
3667 	 * First, call the fini functions.
3668 	 */
3669 	objlist_call_fini(&list_fini, root, lockstate);
3670 
3671 	unref_dag(root);
3672 
3673 	/* Finish cleaning up the newly-unreferenced objects. */
3674 	GDB_STATE(RT_DELETE,&root->linkmap);
3675 	unload_object(root, lockstate);
3676 	GDB_STATE(RT_CONSISTENT,NULL);
3677     } else
3678 	unref_dag(root);
3679 
3680     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
3681     return (0);
3682 }
3683 
3684 char *
3685 dlerror(void)
3686 {
3687 	if (*(lockinfo.dlerror_seen()) != 0)
3688 		return (NULL);
3689 	*lockinfo.dlerror_seen() = 1;
3690 	return (lockinfo.dlerror_loc());
3691 }
3692 
3693 /*
3694  * This function is deprecated and has no effect.
3695  */
3696 void
3697 dllockinit(void *context,
3698     void *(*_lock_create)(void *context) __unused,
3699     void (*_rlock_acquire)(void *lock) __unused,
3700     void (*_wlock_acquire)(void *lock)  __unused,
3701     void (*_lock_release)(void *lock) __unused,
3702     void (*_lock_destroy)(void *lock) __unused,
3703     void (*context_destroy)(void *context))
3704 {
3705     static void *cur_context;
3706     static void (*cur_context_destroy)(void *);
3707 
3708     /* Just destroy the context from the previous call, if necessary. */
3709     if (cur_context_destroy != NULL)
3710 	cur_context_destroy(cur_context);
3711     cur_context = context;
3712     cur_context_destroy = context_destroy;
3713 }
3714 
3715 void *
3716 dlopen(const char *name, int mode)
3717 {
3718 
3719 	return (rtld_dlopen(name, -1, mode));
3720 }
3721 
3722 void *
3723 fdlopen(int fd, int mode)
3724 {
3725 
3726 	return (rtld_dlopen(NULL, fd, mode));
3727 }
3728 
3729 static void *
3730 rtld_dlopen(const char *name, int fd, int mode)
3731 {
3732     RtldLockState lockstate;
3733     int lo_flags;
3734 
3735     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
3736     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
3737     if (ld_tracing != NULL) {
3738 	rlock_acquire(rtld_bind_lock, &lockstate);
3739 	if (sigsetjmp(lockstate.env, 0) != 0)
3740 	    lock_upgrade(rtld_bind_lock, &lockstate);
3741 	environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate));
3742 	lock_release(rtld_bind_lock, &lockstate);
3743     }
3744     lo_flags = RTLD_LO_DLOPEN;
3745     if (mode & RTLD_NODELETE)
3746 	    lo_flags |= RTLD_LO_NODELETE;
3747     if (mode & RTLD_NOLOAD)
3748 	    lo_flags |= RTLD_LO_NOLOAD;
3749     if (mode & RTLD_DEEPBIND)
3750 	    lo_flags |= RTLD_LO_DEEPBIND;
3751     if (ld_tracing != NULL)
3752 	    lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS;
3753 
3754     return (dlopen_object(name, fd, obj_main, lo_flags,
3755       mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
3756 }
3757 
3758 static void
3759 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate)
3760 {
3761 
3762 	obj->dl_refcount--;
3763 	unref_dag(obj);
3764 	if (obj->refcount == 0)
3765 		unload_object(obj, lockstate);
3766 }
3767 
3768 static Obj_Entry *
3769 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
3770     int mode, RtldLockState *lockstate)
3771 {
3772     Obj_Entry *obj;
3773     Objlist initlist;
3774     RtldLockState mlockstate;
3775     int result;
3776 
3777     dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x",
3778       name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" :
3779       refobj->path, lo_flags, mode);
3780     objlist_init(&initlist);
3781 
3782     if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
3783 	wlock_acquire(rtld_bind_lock, &mlockstate);
3784 	lockstate = &mlockstate;
3785     }
3786     GDB_STATE(RT_ADD,NULL);
3787 
3788     obj = NULL;
3789     if (name == NULL && fd == -1) {
3790 	obj = obj_main;
3791 	obj->refcount++;
3792     } else {
3793 	obj = load_object(name, fd, refobj, lo_flags);
3794     }
3795 
3796     if (obj) {
3797 	obj->dl_refcount++;
3798 	if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
3799 	    objlist_push_tail(&list_global, obj);
3800 
3801 	if (!obj->init_done) {
3802 	    /* We loaded something new and have to init something. */
3803 	    if ((lo_flags & RTLD_LO_DEEPBIND) != 0)
3804 		obj->deepbind = true;
3805 	    result = 0;
3806 	    if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 &&
3807 	      obj->static_tls && !allocate_tls_offset(obj)) {
3808 		_rtld_error("%s: No space available "
3809 		  "for static Thread Local Storage", obj->path);
3810 		result = -1;
3811 	    }
3812 	    if (result != -1)
3813 		result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN |
3814 		  RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE));
3815 	    init_dag(obj);
3816 	    ref_dag(obj);
3817 	    if (result != -1)
3818 		result = rtld_verify_versions(&obj->dagmembers);
3819 	    if (result != -1 && ld_tracing)
3820 		goto trace;
3821 	    if (result == -1 || relocate_object_dag(obj,
3822 	      (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
3823 	      (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3824 	      lockstate) == -1) {
3825 		dlopen_cleanup(obj, lockstate);
3826 		obj = NULL;
3827 	    } else if (lo_flags & RTLD_LO_EARLY) {
3828 		/*
3829 		 * Do not call the init functions for early loaded
3830 		 * filtees.  The image is still not initialized enough
3831 		 * for them to work.
3832 		 *
3833 		 * Our object is found by the global object list and
3834 		 * will be ordered among all init calls done right
3835 		 * before transferring control to main.
3836 		 */
3837 	    } else {
3838 		/* Make list of init functions to call. */
3839 		initlist_add_objects(obj, obj, &initlist);
3840 	    }
3841 	    /*
3842 	     * Process all no_delete or global objects here, given
3843 	     * them own DAGs to prevent their dependencies from being
3844 	     * unloaded.  This has to be done after we have loaded all
3845 	     * of the dependencies, so that we do not miss any.
3846 	     */
3847 	    if (obj != NULL)
3848 		process_z(obj);
3849 	} else {
3850 	    /*
3851 	     * Bump the reference counts for objects on this DAG.  If
3852 	     * this is the first dlopen() call for the object that was
3853 	     * already loaded as a dependency, initialize the dag
3854 	     * starting at it.
3855 	     */
3856 	    init_dag(obj);
3857 	    ref_dag(obj);
3858 
3859 	    if ((lo_flags & RTLD_LO_TRACE) != 0)
3860 		goto trace;
3861 	}
3862 	if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
3863 	  obj->z_nodelete) && !obj->ref_nodel) {
3864 	    dbg("obj %s nodelete", obj->path);
3865 	    ref_dag(obj);
3866 	    obj->z_nodelete = obj->ref_nodel = true;
3867 	}
3868     }
3869 
3870     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
3871 	name);
3872     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
3873 
3874     if ((lo_flags & RTLD_LO_EARLY) == 0) {
3875 	map_stacks_exec(lockstate);
3876 	if (obj != NULL)
3877 	    distribute_static_tls(&initlist, lockstate);
3878     }
3879 
3880     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
3881       (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
3882       lockstate) == -1) {
3883 	objlist_clear(&initlist);
3884 	dlopen_cleanup(obj, lockstate);
3885 	if (lockstate == &mlockstate)
3886 	    lock_release(rtld_bind_lock, lockstate);
3887 	return (NULL);
3888     }
3889 
3890     if (!(lo_flags & RTLD_LO_EARLY)) {
3891 	/* Call the init functions. */
3892 	objlist_call_init(&initlist, lockstate);
3893     }
3894     objlist_clear(&initlist);
3895     if (lockstate == &mlockstate)
3896 	lock_release(rtld_bind_lock, lockstate);
3897     return (obj);
3898 trace:
3899     trace_loaded_objects(obj, false);
3900     if (lockstate == &mlockstate)
3901 	lock_release(rtld_bind_lock, lockstate);
3902     exit(0);
3903 }
3904 
3905 static void *
3906 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
3907     int flags)
3908 {
3909     DoneList donelist;
3910     const Obj_Entry *obj, *defobj;
3911     const Elf_Sym *def;
3912     SymLook req;
3913     RtldLockState lockstate;
3914     tls_index ti;
3915     void *sym;
3916     int res;
3917 
3918     def = NULL;
3919     defobj = NULL;
3920     symlook_init(&req, name);
3921     req.ventry = ve;
3922     req.flags = flags | SYMLOOK_IN_PLT;
3923     req.lockstate = &lockstate;
3924 
3925     LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name);
3926     rlock_acquire(rtld_bind_lock, &lockstate);
3927     if (sigsetjmp(lockstate.env, 0) != 0)
3928 	    lock_upgrade(rtld_bind_lock, &lockstate);
3929     if (handle == NULL || handle == RTLD_NEXT ||
3930 	handle == RTLD_DEFAULT || handle == RTLD_SELF) {
3931 
3932 	if ((obj = obj_from_addr(retaddr)) == NULL) {
3933 	    _rtld_error("Cannot determine caller's shared object");
3934 	    lock_release(rtld_bind_lock, &lockstate);
3935 	    LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3936 	    return (NULL);
3937 	}
3938 	if (handle == NULL) {	/* Just the caller's shared object. */
3939 	    res = symlook_obj(&req, obj);
3940 	    if (res == 0) {
3941 		def = req.sym_out;
3942 		defobj = req.defobj_out;
3943 	    }
3944 	} else if (handle == RTLD_NEXT || /* Objects after caller's */
3945 		   handle == RTLD_SELF) { /* ... caller included */
3946 	    if (handle == RTLD_NEXT)
3947 		obj = globallist_next(obj);
3948 	    for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
3949 		if (obj->marker)
3950 		    continue;
3951 		res = symlook_obj(&req, obj);
3952 		if (res == 0) {
3953 		    if (def == NULL || (ld_dynamic_weak &&
3954                       ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) {
3955 			def = req.sym_out;
3956 			defobj = req.defobj_out;
3957 			if (!ld_dynamic_weak ||
3958 			  ELF_ST_BIND(def->st_info) != STB_WEAK)
3959 			    break;
3960 		    }
3961 		}
3962 	    }
3963 	    /*
3964 	     * Search the dynamic linker itself, and possibly resolve the
3965 	     * symbol from there.  This is how the application links to
3966 	     * dynamic linker services such as dlopen.
3967 	     * Note that we ignore ld_dynamic_weak == false case,
3968 	     * always overriding weak symbols by rtld definitions.
3969 	     */
3970 	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
3971 		res = symlook_obj(&req, &obj_rtld);
3972 		if (res == 0) {
3973 		    def = req.sym_out;
3974 		    defobj = req.defobj_out;
3975 		}
3976 	    }
3977 	} else {
3978 	    assert(handle == RTLD_DEFAULT);
3979 	    res = symlook_default(&req, obj);
3980 	    if (res == 0) {
3981 		defobj = req.defobj_out;
3982 		def = req.sym_out;
3983 	    }
3984 	}
3985     } else {
3986 	if ((obj = dlcheck(handle)) == NULL) {
3987 	    lock_release(rtld_bind_lock, &lockstate);
3988 	    LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
3989 	    return (NULL);
3990 	}
3991 
3992 	donelist_init(&donelist);
3993 	if (obj->mainprog) {
3994             /* Handle obtained by dlopen(NULL, ...) implies global scope. */
3995 	    res = symlook_global(&req, &donelist);
3996 	    if (res == 0) {
3997 		def = req.sym_out;
3998 		defobj = req.defobj_out;
3999 	    }
4000 	    /*
4001 	     * Search the dynamic linker itself, and possibly resolve the
4002 	     * symbol from there.  This is how the application links to
4003 	     * dynamic linker services such as dlopen.
4004 	     */
4005 	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
4006 		res = symlook_obj(&req, &obj_rtld);
4007 		if (res == 0) {
4008 		    def = req.sym_out;
4009 		    defobj = req.defobj_out;
4010 		}
4011 	    }
4012 	}
4013 	else {
4014 	    /* Search the whole DAG rooted at the given object. */
4015 	    res = symlook_list(&req, &obj->dagmembers, &donelist);
4016 	    if (res == 0) {
4017 		def = req.sym_out;
4018 		defobj = req.defobj_out;
4019 	    }
4020 	}
4021     }
4022 
4023     if (def != NULL) {
4024 	lock_release(rtld_bind_lock, &lockstate);
4025 
4026 	/*
4027 	 * The value required by the caller is derived from the value
4028 	 * of the symbol. this is simply the relocated value of the
4029 	 * symbol.
4030 	 */
4031 	if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
4032 	    sym = make_function_pointer(def, defobj);
4033 	else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
4034 	    sym = rtld_resolve_ifunc(defobj, def);
4035 	else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
4036 	    ti.ti_module = defobj->tlsindex;
4037 	    ti.ti_offset = def->st_value;
4038 	    sym = __tls_get_addr(&ti);
4039 	} else
4040 	    sym = defobj->relocbase + def->st_value;
4041 	LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name);
4042 	return (sym);
4043     }
4044 
4045     _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "",
4046       ve != NULL ? ve->name : "");
4047     lock_release(rtld_bind_lock, &lockstate);
4048     LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name);
4049     return (NULL);
4050 }
4051 
4052 void *
4053 dlsym(void *handle, const char *name)
4054 {
4055 	return (do_dlsym(handle, name, __builtin_return_address(0), NULL,
4056 	    SYMLOOK_DLSYM));
4057 }
4058 
4059 dlfunc_t
4060 dlfunc(void *handle, const char *name)
4061 {
4062 	union {
4063 		void *d;
4064 		dlfunc_t f;
4065 	} rv;
4066 
4067 	rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
4068 	    SYMLOOK_DLSYM);
4069 	return (rv.f);
4070 }
4071 
4072 void *
4073 dlvsym(void *handle, const char *name, const char *version)
4074 {
4075 	Ver_Entry ventry;
4076 
4077 	ventry.name = version;
4078 	ventry.file = NULL;
4079 	ventry.hash = elf_hash(version);
4080 	ventry.flags= 0;
4081 	return (do_dlsym(handle, name, __builtin_return_address(0), &ventry,
4082 	    SYMLOOK_DLSYM));
4083 }
4084 
4085 int
4086 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
4087 {
4088     const Obj_Entry *obj;
4089     RtldLockState lockstate;
4090 
4091     rlock_acquire(rtld_bind_lock, &lockstate);
4092     obj = obj_from_addr(addr);
4093     if (obj == NULL) {
4094         _rtld_error("No shared object contains address");
4095 	lock_release(rtld_bind_lock, &lockstate);
4096         return (0);
4097     }
4098     rtld_fill_dl_phdr_info(obj, phdr_info);
4099     lock_release(rtld_bind_lock, &lockstate);
4100     return (1);
4101 }
4102 
4103 int
4104 dladdr(const void *addr, Dl_info *info)
4105 {
4106     const Obj_Entry *obj;
4107     const Elf_Sym *def;
4108     void *symbol_addr;
4109     unsigned long symoffset;
4110     RtldLockState lockstate;
4111 
4112     rlock_acquire(rtld_bind_lock, &lockstate);
4113     obj = obj_from_addr(addr);
4114     if (obj == NULL) {
4115         _rtld_error("No shared object contains address");
4116 	lock_release(rtld_bind_lock, &lockstate);
4117         return (0);
4118     }
4119     info->dli_fname = obj->path;
4120     info->dli_fbase = obj->mapbase;
4121     info->dli_saddr = (void *)0;
4122     info->dli_sname = NULL;
4123 
4124     /*
4125      * Walk the symbol list looking for the symbol whose address is
4126      * closest to the address sent in.
4127      */
4128     for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
4129         def = obj->symtab + symoffset;
4130 
4131         /*
4132          * For skip the symbol if st_shndx is either SHN_UNDEF or
4133          * SHN_COMMON.
4134          */
4135         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
4136             continue;
4137 
4138         /*
4139          * If the symbol is greater than the specified address, or if it
4140          * is further away from addr than the current nearest symbol,
4141          * then reject it.
4142          */
4143         symbol_addr = obj->relocbase + def->st_value;
4144         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
4145             continue;
4146 
4147         /* Update our idea of the nearest symbol. */
4148         info->dli_sname = obj->strtab + def->st_name;
4149         info->dli_saddr = symbol_addr;
4150 
4151         /* Exact match? */
4152         if (info->dli_saddr == addr)
4153             break;
4154     }
4155     lock_release(rtld_bind_lock, &lockstate);
4156     return (1);
4157 }
4158 
4159 int
4160 dlinfo(void *handle, int request, void *p)
4161 {
4162     const Obj_Entry *obj;
4163     RtldLockState lockstate;
4164     int error;
4165 
4166     rlock_acquire(rtld_bind_lock, &lockstate);
4167 
4168     if (handle == NULL || handle == RTLD_SELF) {
4169 	void *retaddr;
4170 
4171 	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
4172 	if ((obj = obj_from_addr(retaddr)) == NULL)
4173 	    _rtld_error("Cannot determine caller's shared object");
4174     } else
4175 	obj = dlcheck(handle);
4176 
4177     if (obj == NULL) {
4178 	lock_release(rtld_bind_lock, &lockstate);
4179 	return (-1);
4180     }
4181 
4182     error = 0;
4183     switch (request) {
4184     case RTLD_DI_LINKMAP:
4185 	*((struct link_map const **)p) = &obj->linkmap;
4186 	break;
4187     case RTLD_DI_ORIGIN:
4188 	error = rtld_dirname(obj->path, p);
4189 	break;
4190 
4191     case RTLD_DI_SERINFOSIZE:
4192     case RTLD_DI_SERINFO:
4193 	error = do_search_info(obj, request, (struct dl_serinfo *)p);
4194 	break;
4195 
4196     default:
4197 	_rtld_error("Invalid request %d passed to dlinfo()", request);
4198 	error = -1;
4199     }
4200 
4201     lock_release(rtld_bind_lock, &lockstate);
4202 
4203     return (error);
4204 }
4205 
4206 static void
4207 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
4208 {
4209 	uintptr_t **dtvp;
4210 
4211 	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
4212 	phdr_info->dlpi_name = obj->path;
4213 	phdr_info->dlpi_phdr = obj->phdr;
4214 	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
4215 	phdr_info->dlpi_tls_modid = obj->tlsindex;
4216 	dtvp = &_tcb_get()->tcb_dtv;
4217 	phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp,
4218 	    obj->tlsindex, 0, true) + TLS_DTV_OFFSET;
4219 	phdr_info->dlpi_adds = obj_loads;
4220 	phdr_info->dlpi_subs = obj_loads - obj_count;
4221 }
4222 
4223 int
4224 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
4225 {
4226 	struct dl_phdr_info phdr_info;
4227 	Obj_Entry *obj, marker;
4228 	RtldLockState bind_lockstate, phdr_lockstate;
4229 	int error;
4230 
4231 	init_marker(&marker);
4232 	error = 0;
4233 
4234 	wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
4235 	wlock_acquire(rtld_bind_lock, &bind_lockstate);
4236 	for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) {
4237 		TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next);
4238 		rtld_fill_dl_phdr_info(obj, &phdr_info);
4239 		hold_object(obj);
4240 		lock_release(rtld_bind_lock, &bind_lockstate);
4241 
4242 		error = callback(&phdr_info, sizeof phdr_info, param);
4243 
4244 		wlock_acquire(rtld_bind_lock, &bind_lockstate);
4245 		unhold_object(obj);
4246 		obj = globallist_next(&marker);
4247 		TAILQ_REMOVE(&obj_list, &marker, next);
4248 		if (error != 0) {
4249 			lock_release(rtld_bind_lock, &bind_lockstate);
4250 			lock_release(rtld_phdr_lock, &phdr_lockstate);
4251 			return (error);
4252 		}
4253 	}
4254 
4255 	if (error == 0) {
4256 		rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info);
4257 		lock_release(rtld_bind_lock, &bind_lockstate);
4258 		error = callback(&phdr_info, sizeof(phdr_info), param);
4259 	}
4260 	lock_release(rtld_phdr_lock, &phdr_lockstate);
4261 	return (error);
4262 }
4263 
4264 static void *
4265 fill_search_info(const char *dir, size_t dirlen, void *param)
4266 {
4267     struct fill_search_info_args *arg;
4268 
4269     arg = param;
4270 
4271     if (arg->request == RTLD_DI_SERINFOSIZE) {
4272 	arg->serinfo->dls_cnt ++;
4273 	arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1;
4274     } else {
4275 	struct dl_serpath *s_entry;
4276 
4277 	s_entry = arg->serpath;
4278 	s_entry->dls_name  = arg->strspace;
4279 	s_entry->dls_flags = arg->flags;
4280 
4281 	strncpy(arg->strspace, dir, dirlen);
4282 	arg->strspace[dirlen] = '\0';
4283 
4284 	arg->strspace += dirlen + 1;
4285 	arg->serpath++;
4286     }
4287 
4288     return (NULL);
4289 }
4290 
4291 static int
4292 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
4293 {
4294     struct dl_serinfo _info;
4295     struct fill_search_info_args args;
4296 
4297     args.request = RTLD_DI_SERINFOSIZE;
4298     args.serinfo = &_info;
4299 
4300     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
4301     _info.dls_cnt  = 0;
4302 
4303     path_enumerate(obj->rpath, fill_search_info, NULL, &args);
4304     path_enumerate(ld_library_path, fill_search_info, NULL, &args);
4305     path_enumerate(obj->runpath, fill_search_info, NULL, &args);
4306     path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args);
4307     if (!obj->z_nodeflib)
4308       path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args);
4309 
4310 
4311     if (request == RTLD_DI_SERINFOSIZE) {
4312 	info->dls_size = _info.dls_size;
4313 	info->dls_cnt = _info.dls_cnt;
4314 	return (0);
4315     }
4316 
4317     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
4318 	_rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
4319 	return (-1);
4320     }
4321 
4322     args.request  = RTLD_DI_SERINFO;
4323     args.serinfo  = info;
4324     args.serpath  = &info->dls_serpath[0];
4325     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
4326 
4327     args.flags = LA_SER_RUNPATH;
4328     if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL)
4329 	return (-1);
4330 
4331     args.flags = LA_SER_LIBPATH;
4332     if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL)
4333 	return (-1);
4334 
4335     args.flags = LA_SER_RUNPATH;
4336     if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL)
4337 	return (-1);
4338 
4339     args.flags = LA_SER_CONFIG;
4340     if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args)
4341       != NULL)
4342 	return (-1);
4343 
4344     args.flags = LA_SER_DEFAULT;
4345     if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path,
4346       fill_search_info, NULL, &args) != NULL)
4347 	return (-1);
4348     return (0);
4349 }
4350 
4351 static int
4352 rtld_dirname(const char *path, char *bname)
4353 {
4354     const char *endp;
4355 
4356     /* Empty or NULL string gets treated as "." */
4357     if (path == NULL || *path == '\0') {
4358 	bname[0] = '.';
4359 	bname[1] = '\0';
4360 	return (0);
4361     }
4362 
4363     /* Strip trailing slashes */
4364     endp = path + strlen(path) - 1;
4365     while (endp > path && *endp == '/')
4366 	endp--;
4367 
4368     /* Find the start of the dir */
4369     while (endp > path && *endp != '/')
4370 	endp--;
4371 
4372     /* Either the dir is "/" or there are no slashes */
4373     if (endp == path) {
4374 	bname[0] = *endp == '/' ? '/' : '.';
4375 	bname[1] = '\0';
4376 	return (0);
4377     } else {
4378 	do {
4379 	    endp--;
4380 	} while (endp > path && *endp == '/');
4381     }
4382 
4383     if (endp - path + 2 > PATH_MAX)
4384     {
4385 	_rtld_error("Filename is too long: %s", path);
4386 	return(-1);
4387     }
4388 
4389     strncpy(bname, path, endp - path + 1);
4390     bname[endp - path + 1] = '\0';
4391     return (0);
4392 }
4393 
4394 static int
4395 rtld_dirname_abs(const char *path, char *base)
4396 {
4397 	char *last;
4398 
4399 	if (realpath(path, base) == NULL) {
4400 		_rtld_error("realpath \"%s\" failed (%s)", path,
4401 		    rtld_strerror(errno));
4402 		return (-1);
4403 	}
4404 	dbg("%s -> %s", path, base);
4405 	last = strrchr(base, '/');
4406 	if (last == NULL) {
4407 		_rtld_error("non-abs result from realpath \"%s\"", path);
4408 		return (-1);
4409 	}
4410 	if (last != base)
4411 		*last = '\0';
4412 	return (0);
4413 }
4414 
4415 static void
4416 linkmap_add(Obj_Entry *obj)
4417 {
4418 	struct link_map *l, *prev;
4419 
4420 	l = &obj->linkmap;
4421 	l->l_name = obj->path;
4422 	l->l_base = obj->mapbase;
4423 	l->l_ld = obj->dynamic;
4424 	l->l_addr = obj->relocbase;
4425 
4426 	if (r_debug.r_map == NULL) {
4427 		r_debug.r_map = l;
4428 		return;
4429 	}
4430 
4431 	/*
4432 	 * Scan to the end of the list, but not past the entry for the
4433 	 * dynamic linker, which we want to keep at the very end.
4434 	 */
4435 	for (prev = r_debug.r_map;
4436 	    prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
4437 	     prev = prev->l_next)
4438 		;
4439 
4440 	/* Link in the new entry. */
4441 	l->l_prev = prev;
4442 	l->l_next = prev->l_next;
4443 	if (l->l_next != NULL)
4444 		l->l_next->l_prev = l;
4445 	prev->l_next = l;
4446 }
4447 
4448 static void
4449 linkmap_delete(Obj_Entry *obj)
4450 {
4451 	struct link_map *l;
4452 
4453 	l = &obj->linkmap;
4454 	if (l->l_prev == NULL) {
4455 		if ((r_debug.r_map = l->l_next) != NULL)
4456 			l->l_next->l_prev = NULL;
4457 		return;
4458 	}
4459 
4460 	if ((l->l_prev->l_next = l->l_next) != NULL)
4461 		l->l_next->l_prev = l->l_prev;
4462 }
4463 
4464 /*
4465  * Function for the debugger to set a breakpoint on to gain control.
4466  *
4467  * The two parameters allow the debugger to easily find and determine
4468  * what the runtime loader is doing and to whom it is doing it.
4469  *
4470  * When the loadhook trap is hit (r_debug_state, set at program
4471  * initialization), the arguments can be found on the stack:
4472  *
4473  *  +8   struct link_map *m
4474  *  +4   struct r_debug  *rd
4475  *  +0   RetAddr
4476  */
4477 void
4478 r_debug_state(struct r_debug* rd __unused, struct link_map *m  __unused)
4479 {
4480     /*
4481      * The following is a hack to force the compiler to emit calls to
4482      * this function, even when optimizing.  If the function is empty,
4483      * the compiler is not obliged to emit any code for calls to it,
4484      * even when marked __noinline.  However, gdb depends on those
4485      * calls being made.
4486      */
4487     __compiler_membar();
4488 }
4489 
4490 /*
4491  * A function called after init routines have completed. This can be used to
4492  * break before a program's entry routine is called, and can be used when
4493  * main is not available in the symbol table.
4494  */
4495 void
4496 _r_debug_postinit(struct link_map *m __unused)
4497 {
4498 
4499 	/* See r_debug_state(). */
4500 	__compiler_membar();
4501 }
4502 
4503 static void
4504 release_object(Obj_Entry *obj)
4505 {
4506 
4507 	if (obj->holdcount > 0) {
4508 		obj->unholdfree = true;
4509 		return;
4510 	}
4511 	munmap(obj->mapbase, obj->mapsize);
4512 	linkmap_delete(obj);
4513 	obj_free(obj);
4514 }
4515 
4516 /*
4517  * Get address of the pointer variable in the main program.
4518  * Prefer non-weak symbol over the weak one.
4519  */
4520 static const void **
4521 get_program_var_addr(const char *name, RtldLockState *lockstate)
4522 {
4523     SymLook req;
4524     DoneList donelist;
4525 
4526     symlook_init(&req, name);
4527     req.lockstate = lockstate;
4528     donelist_init(&donelist);
4529     if (symlook_global(&req, &donelist) != 0)
4530 	return (NULL);
4531     if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
4532 	return ((const void **)make_function_pointer(req.sym_out,
4533 	  req.defobj_out));
4534     else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
4535 	return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
4536     else
4537 	return ((const void **)(req.defobj_out->relocbase +
4538 	  req.sym_out->st_value));
4539 }
4540 
4541 /*
4542  * Set a pointer variable in the main program to the given value.  This
4543  * is used to set key variables such as "environ" before any of the
4544  * init functions are called.
4545  */
4546 static void
4547 set_program_var(const char *name, const void *value)
4548 {
4549     const void **addr;
4550 
4551     if ((addr = get_program_var_addr(name, NULL)) != NULL) {
4552 	dbg("\"%s\": *%p <-- %p", name, addr, value);
4553 	*addr = value;
4554     }
4555 }
4556 
4557 /*
4558  * Search the global objects, including dependencies and main object,
4559  * for the given symbol.
4560  */
4561 static int
4562 symlook_global(SymLook *req, DoneList *donelist)
4563 {
4564     SymLook req1;
4565     const Objlist_Entry *elm;
4566     int res;
4567 
4568     symlook_init_from_req(&req1, req);
4569 
4570     /* Search all objects loaded at program start up. */
4571     if (req->defobj_out == NULL || (ld_dynamic_weak &&
4572       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) {
4573 	res = symlook_list(&req1, &list_main, donelist);
4574 	if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL ||
4575 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4576 	    req->sym_out = req1.sym_out;
4577 	    req->defobj_out = req1.defobj_out;
4578 	    assert(req->defobj_out != NULL);
4579 	}
4580     }
4581 
4582     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
4583     STAILQ_FOREACH(elm, &list_global, link) {
4584 	if (req->defobj_out != NULL && (!ld_dynamic_weak ||
4585           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4586 	    break;
4587 	res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
4588 	if (res == 0 && (req->defobj_out == NULL ||
4589 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4590 	    req->sym_out = req1.sym_out;
4591 	    req->defobj_out = req1.defobj_out;
4592 	    assert(req->defobj_out != NULL);
4593 	}
4594     }
4595 
4596     return (req->sym_out != NULL ? 0 : ESRCH);
4597 }
4598 
4599 /*
4600  * Given a symbol name in a referencing object, find the corresponding
4601  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
4602  * no definition was found.  Returns a pointer to the Obj_Entry of the
4603  * defining object via the reference parameter DEFOBJ_OUT.
4604  */
4605 static int
4606 symlook_default(SymLook *req, const Obj_Entry *refobj)
4607 {
4608     DoneList donelist;
4609     const Objlist_Entry *elm;
4610     SymLook req1;
4611     int res;
4612 
4613     donelist_init(&donelist);
4614     symlook_init_from_req(&req1, req);
4615 
4616     /*
4617      * Look first in the referencing object if linked symbolically,
4618      * and similarly handle protected symbols.
4619      */
4620     res = symlook_obj(&req1, refobj);
4621     if (res == 0 && (refobj->symbolic ||
4622       ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) {
4623 	req->sym_out = req1.sym_out;
4624 	req->defobj_out = req1.defobj_out;
4625 	assert(req->defobj_out != NULL);
4626     }
4627     if (refobj->symbolic || req->defobj_out != NULL)
4628 	donelist_check(&donelist, refobj);
4629 
4630     if (!refobj->deepbind)
4631         symlook_global(req, &donelist);
4632 
4633     /* Search all dlopened DAGs containing the referencing object. */
4634     STAILQ_FOREACH(elm, &refobj->dldags, link) {
4635 	if (req->sym_out != NULL && (!ld_dynamic_weak ||
4636           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK))
4637 	    break;
4638 	res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
4639 	if (res == 0 && (req->sym_out == NULL ||
4640 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4641 	    req->sym_out = req1.sym_out;
4642 	    req->defobj_out = req1.defobj_out;
4643 	    assert(req->defobj_out != NULL);
4644 	}
4645     }
4646 
4647     if (refobj->deepbind)
4648         symlook_global(req, &donelist);
4649 
4650     /*
4651      * Search the dynamic linker itself, and possibly resolve the
4652      * symbol from there.  This is how the application links to
4653      * dynamic linker services such as dlopen.
4654      */
4655     if (req->sym_out == NULL ||
4656       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
4657 	res = symlook_obj(&req1, &obj_rtld);
4658 	if (res == 0) {
4659 	    req->sym_out = req1.sym_out;
4660 	    req->defobj_out = req1.defobj_out;
4661 	    assert(req->defobj_out != NULL);
4662 	}
4663     }
4664 
4665     return (req->sym_out != NULL ? 0 : ESRCH);
4666 }
4667 
4668 static int
4669 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
4670 {
4671     const Elf_Sym *def;
4672     const Obj_Entry *defobj;
4673     const Objlist_Entry *elm;
4674     SymLook req1;
4675     int res;
4676 
4677     def = NULL;
4678     defobj = NULL;
4679     STAILQ_FOREACH(elm, objlist, link) {
4680 	if (donelist_check(dlp, elm->obj))
4681 	    continue;
4682 	symlook_init_from_req(&req1, req);
4683 	if ((res = symlook_obj(&req1, elm->obj)) == 0) {
4684 	    if (def == NULL || (ld_dynamic_weak &&
4685               ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4686 		def = req1.sym_out;
4687 		defobj = req1.defobj_out;
4688 		if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4689 		    break;
4690 	    }
4691 	}
4692     }
4693     if (def != NULL) {
4694 	req->sym_out = def;
4695 	req->defobj_out = defobj;
4696 	return (0);
4697     }
4698     return (ESRCH);
4699 }
4700 
4701 /*
4702  * Search the chain of DAGS cointed to by the given Needed_Entry
4703  * for a symbol of the given name.  Each DAG is scanned completely
4704  * before advancing to the next one.  Returns a pointer to the symbol,
4705  * or NULL if no definition was found.
4706  */
4707 static int
4708 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
4709 {
4710     const Elf_Sym *def;
4711     const Needed_Entry *n;
4712     const Obj_Entry *defobj;
4713     SymLook req1;
4714     int res;
4715 
4716     def = NULL;
4717     defobj = NULL;
4718     symlook_init_from_req(&req1, req);
4719     for (n = needed; n != NULL; n = n->next) {
4720 	if (n->obj == NULL ||
4721 	    (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
4722 	    continue;
4723 	if (def == NULL || (ld_dynamic_weak &&
4724           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
4725 	    def = req1.sym_out;
4726 	    defobj = req1.defobj_out;
4727 	    if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK)
4728 		break;
4729 	}
4730     }
4731     if (def != NULL) {
4732 	req->sym_out = def;
4733 	req->defobj_out = defobj;
4734 	return (0);
4735     }
4736     return (ESRCH);
4737 }
4738 
4739 static int
4740 symlook_obj_load_filtees(SymLook *req, SymLook *req1, const Obj_Entry *obj,
4741     Needed_Entry *needed)
4742 {
4743 	DoneList donelist;
4744 	int flags;
4745 
4746 	flags = (req->flags & SYMLOOK_EARLY) != 0 ? RTLD_LO_EARLY : 0;
4747 	load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
4748 	donelist_init(&donelist);
4749 	symlook_init_from_req(req1, req);
4750 	return (symlook_needed(req1, needed, &donelist));
4751 }
4752 
4753 /*
4754  * Search the symbol table of a single shared object for a symbol of
4755  * the given name and version, if requested.  Returns a pointer to the
4756  * symbol, or NULL if no definition was found.  If the object is
4757  * filter, return filtered symbol from filtee.
4758  *
4759  * The symbol's hash value is passed in for efficiency reasons; that
4760  * eliminates many recomputations of the hash value.
4761  */
4762 int
4763 symlook_obj(SymLook *req, const Obj_Entry *obj)
4764 {
4765     SymLook req1;
4766     int res, mres;
4767 
4768     /*
4769      * If there is at least one valid hash at this point, we prefer to
4770      * use the faster GNU version if available.
4771      */
4772     if (obj->valid_hash_gnu)
4773 	mres = symlook_obj1_gnu(req, obj);
4774     else if (obj->valid_hash_sysv)
4775 	mres = symlook_obj1_sysv(req, obj);
4776     else
4777 	return (EINVAL);
4778 
4779     if (mres == 0) {
4780 	if (obj->needed_filtees != NULL) {
4781 	    res = symlook_obj_load_filtees(req, &req1, obj,
4782 		obj->needed_filtees);
4783 	    if (res == 0) {
4784 		req->sym_out = req1.sym_out;
4785 		req->defobj_out = req1.defobj_out;
4786 	    }
4787 	    return (res);
4788 	}
4789 	if (obj->needed_aux_filtees != NULL) {
4790 	    res = symlook_obj_load_filtees(req, &req1, obj,
4791 		obj->needed_aux_filtees);
4792 	    if (res == 0) {
4793 		req->sym_out = req1.sym_out;
4794 		req->defobj_out = req1.defobj_out;
4795 		return (res);
4796 	    }
4797 	}
4798     }
4799     return (mres);
4800 }
4801 
4802 /* Symbol match routine common to both hash functions */
4803 static bool
4804 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
4805     const unsigned long symnum)
4806 {
4807 	Elf_Versym verndx;
4808 	const Elf_Sym *symp;
4809 	const char *strp;
4810 
4811 	symp = obj->symtab + symnum;
4812 	strp = obj->strtab + symp->st_name;
4813 
4814 	switch (ELF_ST_TYPE(symp->st_info)) {
4815 	case STT_FUNC:
4816 	case STT_NOTYPE:
4817 	case STT_OBJECT:
4818 	case STT_COMMON:
4819 	case STT_GNU_IFUNC:
4820 		if (symp->st_value == 0)
4821 			return (false);
4822 		/* fallthrough */
4823 	case STT_TLS:
4824 		if (symp->st_shndx != SHN_UNDEF)
4825 			break;
4826 		else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
4827 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
4828 			break;
4829 		/* fallthrough */
4830 	default:
4831 		return (false);
4832 	}
4833 	if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
4834 		return (false);
4835 
4836 	if (req->ventry == NULL) {
4837 		if (obj->versyms != NULL) {
4838 			verndx = VER_NDX(obj->versyms[symnum]);
4839 			if (verndx > obj->vernum) {
4840 				_rtld_error(
4841 				    "%s: symbol %s references wrong version %d",
4842 				    obj->path, obj->strtab + symnum, verndx);
4843 				return (false);
4844 			}
4845 			/*
4846 			 * If we are not called from dlsym (i.e. this
4847 			 * is a normal relocation from unversioned
4848 			 * binary), accept the symbol immediately if
4849 			 * it happens to have first version after this
4850 			 * shared object became versioned.  Otherwise,
4851 			 * if symbol is versioned and not hidden,
4852 			 * remember it. If it is the only symbol with
4853 			 * this name exported by the shared object, it
4854 			 * will be returned as a match by the calling
4855 			 * function. If symbol is global (verndx < 2)
4856 			 * accept it unconditionally.
4857 			 */
4858 			if ((req->flags & SYMLOOK_DLSYM) == 0 &&
4859 			    verndx == VER_NDX_GIVEN) {
4860 				result->sym_out = symp;
4861 				return (true);
4862 			}
4863 			else if (verndx >= VER_NDX_GIVEN) {
4864 				if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
4865 				    == 0) {
4866 					if (result->vsymp == NULL)
4867 						result->vsymp = symp;
4868 					result->vcount++;
4869 				}
4870 				return (false);
4871 			}
4872 		}
4873 		result->sym_out = symp;
4874 		return (true);
4875 	}
4876 	if (obj->versyms == NULL) {
4877 		if (object_match_name(obj, req->ventry->name)) {
4878 			_rtld_error("%s: object %s should provide version %s "
4879 			    "for symbol %s", obj_rtld.path, obj->path,
4880 			    req->ventry->name, obj->strtab + symnum);
4881 			return (false);
4882 		}
4883 	} else {
4884 		verndx = VER_NDX(obj->versyms[symnum]);
4885 		if (verndx > obj->vernum) {
4886 			_rtld_error("%s: symbol %s references wrong version %d",
4887 			    obj->path, obj->strtab + symnum, verndx);
4888 			return (false);
4889 		}
4890 		if (obj->vertab[verndx].hash != req->ventry->hash ||
4891 		    strcmp(obj->vertab[verndx].name, req->ventry->name)) {
4892 			/*
4893 			 * Version does not match. Look if this is a
4894 			 * global symbol and if it is not hidden. If
4895 			 * global symbol (verndx < 2) is available,
4896 			 * use it. Do not return symbol if we are
4897 			 * called by dlvsym, because dlvsym looks for
4898 			 * a specific version and default one is not
4899 			 * what dlvsym wants.
4900 			 */
4901 			if ((req->flags & SYMLOOK_DLSYM) ||
4902 			    (verndx >= VER_NDX_GIVEN) ||
4903 			    (obj->versyms[symnum] & VER_NDX_HIDDEN))
4904 				return (false);
4905 		}
4906 	}
4907 	result->sym_out = symp;
4908 	return (true);
4909 }
4910 
4911 /*
4912  * Search for symbol using SysV hash function.
4913  * obj->buckets is known not to be NULL at this point; the test for this was
4914  * performed with the obj->valid_hash_sysv assignment.
4915  */
4916 static int
4917 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
4918 {
4919 	unsigned long symnum;
4920 	Sym_Match_Result matchres;
4921 
4922 	matchres.sym_out = NULL;
4923 	matchres.vsymp = NULL;
4924 	matchres.vcount = 0;
4925 
4926 	for (symnum = obj->buckets[req->hash % obj->nbuckets];
4927 	    symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
4928 		if (symnum >= obj->nchains)
4929 			return (ESRCH);	/* Bad object */
4930 
4931 		if (matched_symbol(req, obj, &matchres, symnum)) {
4932 			req->sym_out = matchres.sym_out;
4933 			req->defobj_out = obj;
4934 			return (0);
4935 		}
4936 	}
4937 	if (matchres.vcount == 1) {
4938 		req->sym_out = matchres.vsymp;
4939 		req->defobj_out = obj;
4940 		return (0);
4941 	}
4942 	return (ESRCH);
4943 }
4944 
4945 /* Search for symbol using GNU hash function */
4946 static int
4947 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
4948 {
4949 	Elf_Addr bloom_word;
4950 	const Elf32_Word *hashval;
4951 	Elf32_Word bucket;
4952 	Sym_Match_Result matchres;
4953 	unsigned int h1, h2;
4954 	unsigned long symnum;
4955 
4956 	matchres.sym_out = NULL;
4957 	matchres.vsymp = NULL;
4958 	matchres.vcount = 0;
4959 
4960 	/* Pick right bitmask word from Bloom filter array */
4961 	bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
4962 	    obj->maskwords_bm_gnu];
4963 
4964 	/* Calculate modulus word size of gnu hash and its derivative */
4965 	h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
4966 	h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
4967 
4968 	/* Filter out the "definitely not in set" queries */
4969 	if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
4970 		return (ESRCH);
4971 
4972 	/* Locate hash chain and corresponding value element*/
4973 	bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
4974 	if (bucket == 0)
4975 		return (ESRCH);
4976 	hashval = &obj->chain_zero_gnu[bucket];
4977 	do {
4978 		if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
4979 			symnum = hashval - obj->chain_zero_gnu;
4980 			if (matched_symbol(req, obj, &matchres, symnum)) {
4981 				req->sym_out = matchres.sym_out;
4982 				req->defobj_out = obj;
4983 				return (0);
4984 			}
4985 		}
4986 	} while ((*hashval++ & 1) == 0);
4987 	if (matchres.vcount == 1) {
4988 		req->sym_out = matchres.vsymp;
4989 		req->defobj_out = obj;
4990 		return (0);
4991 	}
4992 	return (ESRCH);
4993 }
4994 
4995 static void
4996 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2)
4997 {
4998 	*main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME);
4999 	if (*main_local == NULL)
5000 		*main_local = "";
5001 
5002 	*fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1);
5003 	if (*fmt1 == NULL)
5004 		*fmt1 = "\t%o => %p (%x)\n";
5005 
5006 	*fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2);
5007 	if (*fmt2 == NULL)
5008 		*fmt2 = "\t%o (%x)\n";
5009 }
5010 
5011 static void
5012 trace_print_obj(Obj_Entry *obj, const char *name, const char *path,
5013     const char *main_local, const char *fmt1, const char *fmt2)
5014 {
5015 	const char *fmt;
5016 	int c;
5017 
5018 	if (fmt1 == NULL)
5019 		fmt = fmt2;
5020 	else
5021 		/* XXX bogus */
5022 		fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2;
5023 
5024 	while ((c = *fmt++) != '\0') {
5025 		switch (c) {
5026 		default:
5027 			rtld_putchar(c);
5028 			continue;
5029 		case '\\':
5030 			switch (c = *fmt) {
5031 			case '\0':
5032 				continue;
5033 			case 'n':
5034 				rtld_putchar('\n');
5035 				break;
5036 			case 't':
5037 				rtld_putchar('\t');
5038 				break;
5039 			}
5040 			break;
5041 		case '%':
5042 			switch (c = *fmt) {
5043 			case '\0':
5044 				continue;
5045 			case '%':
5046 			default:
5047 				rtld_putchar(c);
5048 				break;
5049 			case 'A':
5050 				rtld_putstr(main_local);
5051 				break;
5052 			case 'a':
5053 				rtld_putstr(obj_main->path);
5054 				break;
5055 			case 'o':
5056 				rtld_putstr(name);
5057 				break;
5058 			case 'p':
5059 				rtld_putstr(path);
5060 				break;
5061 			case 'x':
5062 				rtld_printf("%p", obj != NULL ?
5063 				    obj->mapbase : NULL);
5064 				break;
5065 			}
5066 			break;
5067 		}
5068 		++fmt;
5069 	}
5070 }
5071 
5072 static void
5073 trace_loaded_objects(Obj_Entry *obj, bool show_preload)
5074 {
5075 	const char *fmt1, *fmt2, *main_local;
5076 	const char *name, *path;
5077 	bool first_spurious, list_containers;
5078 
5079 	trace_calc_fmts(&main_local, &fmt1, &fmt2);
5080 	list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL;
5081 
5082 	for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5083 		Needed_Entry *needed;
5084 
5085 		if (obj->marker)
5086 			continue;
5087 		if (list_containers && obj->needed != NULL)
5088 			rtld_printf("%s:\n", obj->path);
5089 		for (needed = obj->needed; needed; needed = needed->next) {
5090 			if (needed->obj != NULL) {
5091 				if (needed->obj->traced && !list_containers)
5092 					continue;
5093 				needed->obj->traced = true;
5094 				path = needed->obj->path;
5095 			} else
5096 				path = "not found";
5097 
5098 			name = obj->strtab + needed->name;
5099 			trace_print_obj(needed->obj, name, path, main_local,
5100 			    fmt1, fmt2);
5101 		}
5102 	}
5103 
5104 	if (show_preload) {
5105 		if (ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2) == NULL)
5106 			fmt2 = "\t%p (%x)\n";
5107 		first_spurious = true;
5108 
5109 		TAILQ_FOREACH(obj, &obj_list, next) {
5110 			if (obj->marker || obj == obj_main || obj->traced)
5111 				continue;
5112 
5113 			if (list_containers && first_spurious) {
5114 				rtld_printf("[preloaded]\n");
5115 				first_spurious = false;
5116 			}
5117 
5118 			Name_Entry *fname = STAILQ_FIRST(&obj->names);
5119 			name = fname == NULL ? "<unknown>" : fname->name;
5120 			trace_print_obj(obj, name, obj->path, main_local,
5121 			    NULL, fmt2);
5122 		}
5123 	}
5124 }
5125 
5126 /*
5127  * Unload a dlopened object and its dependencies from memory and from
5128  * our data structures.  It is assumed that the DAG rooted in the
5129  * object has already been unreferenced, and that the object has a
5130  * reference count of 0.
5131  */
5132 static void
5133 unload_object(Obj_Entry *root, RtldLockState *lockstate)
5134 {
5135 	Obj_Entry marker, *obj, *next;
5136 
5137 	assert(root->refcount == 0);
5138 
5139 	/*
5140 	 * Pass over the DAG removing unreferenced objects from
5141 	 * appropriate lists.
5142 	 */
5143 	unlink_object(root);
5144 
5145 	/* Unmap all objects that are no longer referenced. */
5146 	for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) {
5147 		next = TAILQ_NEXT(obj, next);
5148 		if (obj->marker || obj->refcount != 0)
5149 			continue;
5150 		LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase,
5151 		    obj->mapsize, 0, obj->path);
5152 		dbg("unloading \"%s\"", obj->path);
5153 		/*
5154 		 * Unlink the object now to prevent new references from
5155 		 * being acquired while the bind lock is dropped in
5156 		 * recursive dlclose() invocations.
5157 		 */
5158 		TAILQ_REMOVE(&obj_list, obj, next);
5159 		obj_count--;
5160 
5161 		if (obj->filtees_loaded) {
5162 			if (next != NULL) {
5163 				init_marker(&marker);
5164 				TAILQ_INSERT_BEFORE(next, &marker, next);
5165 				unload_filtees(obj, lockstate);
5166 				next = TAILQ_NEXT(&marker, next);
5167 				TAILQ_REMOVE(&obj_list, &marker, next);
5168 			} else
5169 				unload_filtees(obj, lockstate);
5170 		}
5171 		release_object(obj);
5172 	}
5173 }
5174 
5175 static void
5176 unlink_object(Obj_Entry *root)
5177 {
5178     Objlist_Entry *elm;
5179 
5180     if (root->refcount == 0) {
5181 	/* Remove the object from the RTLD_GLOBAL list. */
5182 	objlist_remove(&list_global, root);
5183 
5184     	/* Remove the object from all objects' DAG lists. */
5185     	STAILQ_FOREACH(elm, &root->dagmembers, link) {
5186 	    objlist_remove(&elm->obj->dldags, root);
5187 	    if (elm->obj != root)
5188 		unlink_object(elm->obj);
5189 	}
5190     }
5191 }
5192 
5193 static void
5194 ref_dag(Obj_Entry *root)
5195 {
5196     Objlist_Entry *elm;
5197 
5198     assert(root->dag_inited);
5199     STAILQ_FOREACH(elm, &root->dagmembers, link)
5200 	elm->obj->refcount++;
5201 }
5202 
5203 static void
5204 unref_dag(Obj_Entry *root)
5205 {
5206     Objlist_Entry *elm;
5207 
5208     assert(root->dag_inited);
5209     STAILQ_FOREACH(elm, &root->dagmembers, link)
5210 	elm->obj->refcount--;
5211 }
5212 
5213 /*
5214  * Common code for MD __tls_get_addr().
5215  */
5216 static void *
5217 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked)
5218 {
5219 	Elf_Addr *newdtv, *dtv;
5220 	RtldLockState lockstate;
5221 	int to_copy;
5222 
5223 	dtv = *dtvp;
5224 	/* Check dtv generation in case new modules have arrived */
5225 	if (dtv[0] != tls_dtv_generation) {
5226 		if (!locked)
5227 			wlock_acquire(rtld_bind_lock, &lockstate);
5228 		newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5229 		to_copy = dtv[1];
5230 		if (to_copy > tls_max_index)
5231 			to_copy = tls_max_index;
5232 		memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
5233 		newdtv[0] = tls_dtv_generation;
5234 		newdtv[1] = tls_max_index;
5235 		free(dtv);
5236 		if (!locked)
5237 			lock_release(rtld_bind_lock, &lockstate);
5238 		dtv = *dtvp = newdtv;
5239 	}
5240 
5241 	/* Dynamically allocate module TLS if necessary */
5242 	if (dtv[index + 1] == 0) {
5243 		/* Signal safe, wlock will block out signals. */
5244 		if (!locked)
5245 			wlock_acquire(rtld_bind_lock, &lockstate);
5246 		if (!dtv[index + 1])
5247 			dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
5248 		if (!locked)
5249 			lock_release(rtld_bind_lock, &lockstate);
5250 	}
5251 	return ((void *)(dtv[index + 1] + offset));
5252 }
5253 
5254 void *
5255 tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset)
5256 {
5257 	uintptr_t *dtv;
5258 
5259 	dtv = *dtvp;
5260 	/* Check dtv generation in case new modules have arrived */
5261 	if (__predict_true(dtv[0] == tls_dtv_generation &&
5262 	    dtv[index + 1] != 0))
5263 		return ((void *)(dtv[index + 1] + offset));
5264 	return (tls_get_addr_slow(dtvp, index, offset, false));
5265 }
5266 
5267 #ifdef TLS_VARIANT_I
5268 
5269 /*
5270  * Return pointer to allocated TLS block
5271  */
5272 static void *
5273 get_tls_block_ptr(void *tcb, size_t tcbsize)
5274 {
5275     size_t extra_size, post_size, pre_size, tls_block_size;
5276     size_t tls_init_align;
5277 
5278     tls_init_align = MAX(obj_main->tlsalign, 1);
5279 
5280     /* Compute fragments sizes. */
5281     extra_size = tcbsize - TLS_TCB_SIZE;
5282     post_size = calculate_tls_post_size(tls_init_align);
5283     tls_block_size = tcbsize + post_size;
5284     pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5285 
5286     return ((char *)tcb - pre_size - extra_size);
5287 }
5288 
5289 /*
5290  * Allocate Static TLS using the Variant I method.
5291  *
5292  * For details on the layout, see lib/libc/gen/tls.c.
5293  *
5294  * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as
5295  *     it is based on tls_last_offset, and TLS offsets here are really TCB
5296  *     offsets, whereas libc's tls_static_space is just the executable's static
5297  *     TLS segment.
5298  */
5299 void *
5300 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
5301 {
5302     Obj_Entry *obj;
5303     char *tls_block;
5304     Elf_Addr *dtv, **tcb;
5305     Elf_Addr addr;
5306     Elf_Addr i;
5307     size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
5308     size_t tls_init_align, tls_init_offset;
5309 
5310     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
5311 	return (oldtcb);
5312 
5313     assert(tcbsize >= TLS_TCB_SIZE);
5314     maxalign = MAX(tcbalign, tls_static_max_align);
5315     tls_init_align = MAX(obj_main->tlsalign, 1);
5316 
5317     /* Compute fragmets sizes. */
5318     extra_size = tcbsize - TLS_TCB_SIZE;
5319     post_size = calculate_tls_post_size(tls_init_align);
5320     tls_block_size = tcbsize + post_size;
5321     pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size;
5322     tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size;
5323 
5324     /* Allocate whole TLS block */
5325     tls_block = xmalloc_aligned(tls_block_size, maxalign, 0);
5326     tcb = (Elf_Addr **)(tls_block + pre_size + extra_size);
5327 
5328     if (oldtcb != NULL) {
5329 	memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
5330 	    tls_static_space);
5331 	free(get_tls_block_ptr(oldtcb, tcbsize));
5332 
5333 	/* Adjust the DTV. */
5334 	dtv = tcb[0];
5335 	for (i = 0; i < dtv[1]; i++) {
5336 	    if (dtv[i+2] >= (Elf_Addr)oldtcb &&
5337 		dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
5338 		dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb;
5339 	    }
5340 	}
5341     } else {
5342 	dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5343 	tcb[0] = dtv;
5344 	dtv[0] = tls_dtv_generation;
5345 	dtv[1] = tls_max_index;
5346 
5347 	for (obj = globallist_curr(objs); obj != NULL;
5348 	  obj = globallist_next(obj)) {
5349 	    if (obj->tlsoffset == 0)
5350 		continue;
5351 	    tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1);
5352 	    addr = (Elf_Addr)tcb + obj->tlsoffset;
5353 	    if (tls_init_offset > 0)
5354 		memset((void *)addr, 0, tls_init_offset);
5355 	    if (obj->tlsinitsize > 0) {
5356 		memcpy((void *)(addr + tls_init_offset), obj->tlsinit,
5357 		    obj->tlsinitsize);
5358 	    }
5359 	    if (obj->tlssize > obj->tlsinitsize) {
5360 		memset((void *)(addr + tls_init_offset + obj->tlsinitsize),
5361 		    0, obj->tlssize - obj->tlsinitsize - tls_init_offset);
5362 	    }
5363 	    dtv[obj->tlsindex + 1] = addr;
5364 	}
5365     }
5366 
5367     return (tcb);
5368 }
5369 
5370 void
5371 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
5372 {
5373     Elf_Addr *dtv;
5374     Elf_Addr tlsstart, tlsend;
5375     size_t post_size;
5376     size_t dtvsize, i, tls_init_align __unused;
5377 
5378     assert(tcbsize >= TLS_TCB_SIZE);
5379     tls_init_align = MAX(obj_main->tlsalign, 1);
5380 
5381     /* Compute fragments sizes. */
5382     post_size = calculate_tls_post_size(tls_init_align);
5383 
5384     tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size;
5385     tlsend = (Elf_Addr)tcb + tls_static_space;
5386 
5387     dtv = *(Elf_Addr **)tcb;
5388     dtvsize = dtv[1];
5389     for (i = 0; i < dtvsize; i++) {
5390 	if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
5391 	    free((void*)dtv[i+2]);
5392 	}
5393     }
5394     free(dtv);
5395     free(get_tls_block_ptr(tcb, tcbsize));
5396 }
5397 
5398 #endif	/* TLS_VARIANT_I */
5399 
5400 #ifdef TLS_VARIANT_II
5401 
5402 /*
5403  * Allocate Static TLS using the Variant II method.
5404  */
5405 void *
5406 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
5407 {
5408     Obj_Entry *obj;
5409     size_t size, ralign;
5410     char *tls;
5411     Elf_Addr *dtv, *olddtv;
5412     Elf_Addr segbase, oldsegbase, addr;
5413     size_t i;
5414 
5415     ralign = tcbalign;
5416     if (tls_static_max_align > ralign)
5417 	    ralign = tls_static_max_align;
5418     size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign);
5419 
5420     assert(tcbsize >= 2*sizeof(Elf_Addr));
5421     tls = xmalloc_aligned(size, ralign, 0 /* XXX */);
5422     dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
5423 
5424     segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign));
5425     ((Elf_Addr *)segbase)[0] = segbase;
5426     ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv;
5427 
5428     dtv[0] = tls_dtv_generation;
5429     dtv[1] = tls_max_index;
5430 
5431     if (oldtls) {
5432 	/*
5433 	 * Copy the static TLS block over whole.
5434 	 */
5435 	oldsegbase = (Elf_Addr) oldtls;
5436 	memcpy((void *)(segbase - tls_static_space),
5437 	   (const void *)(oldsegbase - tls_static_space),
5438 	   tls_static_space);
5439 
5440 	/*
5441 	 * If any dynamic TLS blocks have been created tls_get_addr(),
5442 	 * move them over.
5443 	 */
5444 	olddtv = ((Elf_Addr **)oldsegbase)[1];
5445 	for (i = 0; i < olddtv[1]; i++) {
5446 	    if (olddtv[i + 2] < oldsegbase - size ||
5447 		olddtv[i + 2] > oldsegbase) {
5448 		    dtv[i + 2] = olddtv[i + 2];
5449 		    olddtv[i + 2] = 0;
5450 	    }
5451 	}
5452 
5453 	/*
5454 	 * We assume that this block was the one we created with
5455 	 * allocate_initial_tls().
5456 	 */
5457 	free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr));
5458     } else {
5459 	for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) {
5460 		if (obj->marker || obj->tlsoffset == 0)
5461 			continue;
5462 		addr = segbase - obj->tlsoffset;
5463 		memset((void *)(addr + obj->tlsinitsize),
5464 		    0, obj->tlssize - obj->tlsinitsize);
5465 		if (obj->tlsinit) {
5466 			memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize);
5467 			obj->static_tls_copied = true;
5468 		}
5469 		dtv[obj->tlsindex + 1] = addr;
5470 	}
5471     }
5472 
5473     return ((void *)segbase);
5474 }
5475 
5476 void
5477 free_tls(void *tls, size_t tcbsize  __unused, size_t tcbalign)
5478 {
5479     Elf_Addr* dtv;
5480     size_t size, ralign;
5481     int dtvsize, i;
5482     Elf_Addr tlsstart, tlsend;
5483 
5484     /*
5485      * Figure out the size of the initial TLS block so that we can
5486      * find stuff which ___tls_get_addr() allocated dynamically.
5487      */
5488     ralign = tcbalign;
5489     if (tls_static_max_align > ralign)
5490 	    ralign = tls_static_max_align;
5491     size = roundup(tls_static_space, ralign);
5492 
5493     dtv = ((Elf_Addr **)tls)[1];
5494     dtvsize = dtv[1];
5495     tlsend = (Elf_Addr)tls;
5496     tlsstart = tlsend - size;
5497     for (i = 0; i < dtvsize; i++) {
5498 	    if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart ||
5499 	        dtv[i + 2] > tlsend)) {
5500 		    free((void *)dtv[i + 2]);
5501 	}
5502     }
5503 
5504     free((void *)tlsstart);
5505     free((void *)dtv);
5506 }
5507 
5508 #endif	/* TLS_VARIANT_II */
5509 
5510 /*
5511  * Allocate TLS block for module with given index.
5512  */
5513 void *
5514 allocate_module_tls(int index)
5515 {
5516 	Obj_Entry *obj;
5517 	char *p;
5518 
5519 	TAILQ_FOREACH(obj, &obj_list, next) {
5520 		if (obj->marker)
5521 			continue;
5522 		if (obj->tlsindex == index)
5523 			break;
5524 	}
5525 	if (obj == NULL) {
5526 		_rtld_error("Can't find module with TLS index %d", index);
5527 		rtld_die();
5528 	}
5529 
5530 	if (obj->tls_static) {
5531 #ifdef TLS_VARIANT_I
5532 		p = (char *)_tcb_get() + obj->tlsoffset + TLS_TCB_SIZE;
5533 #else
5534 		p = (char *)_tcb_get() - obj->tlsoffset;
5535 #endif
5536 		return (p);
5537 	}
5538 
5539 	obj->tls_dynamic = true;
5540 
5541 	p = xmalloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset);
5542 	memcpy(p, obj->tlsinit, obj->tlsinitsize);
5543 	memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
5544 	return (p);
5545 }
5546 
5547 bool
5548 allocate_tls_offset(Obj_Entry *obj)
5549 {
5550     size_t off;
5551 
5552     if (obj->tls_dynamic)
5553 	return (false);
5554 
5555     if (obj->tls_static)
5556 	return (true);
5557 
5558     if (obj->tlssize == 0) {
5559 	obj->tls_static = true;
5560 	return (true);
5561     }
5562 
5563     if (tls_last_offset == 0)
5564 	off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign,
5565 	  obj->tlspoffset);
5566     else
5567 	off = calculate_tls_offset(tls_last_offset, tls_last_size,
5568 	  obj->tlssize, obj->tlsalign, obj->tlspoffset);
5569 
5570     obj->tlsoffset = off;
5571 #ifdef TLS_VARIANT_I
5572     off += obj->tlssize;
5573 #endif
5574 
5575     /*
5576      * If we have already fixed the size of the static TLS block, we
5577      * must stay within that size. When allocating the static TLS, we
5578      * leave a small amount of space spare to be used for dynamically
5579      * loading modules which use static TLS.
5580      */
5581     if (tls_static_space != 0) {
5582 	if (off > tls_static_space)
5583 	    return (false);
5584     } else if (obj->tlsalign > tls_static_max_align) {
5585 	    tls_static_max_align = obj->tlsalign;
5586     }
5587 
5588     tls_last_offset = off;
5589     tls_last_size = obj->tlssize;
5590     obj->tls_static = true;
5591 
5592     return (true);
5593 }
5594 
5595 void
5596 free_tls_offset(Obj_Entry *obj)
5597 {
5598 
5599     /*
5600      * If we were the last thing to allocate out of the static TLS
5601      * block, we give our space back to the 'allocator'. This is a
5602      * simplistic workaround to allow libGL.so.1 to be loaded and
5603      * unloaded multiple times.
5604      */
5605     size_t off = obj->tlsoffset;
5606 #ifdef TLS_VARIANT_I
5607     off += obj->tlssize;
5608 #endif
5609     if (off == tls_last_offset) {
5610 	tls_last_offset -= obj->tlssize;
5611 	tls_last_size = 0;
5612     }
5613 }
5614 
5615 void *
5616 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
5617 {
5618     void *ret;
5619     RtldLockState lockstate;
5620 
5621     wlock_acquire(rtld_bind_lock, &lockstate);
5622     ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls,
5623       tcbsize, tcbalign);
5624     lock_release(rtld_bind_lock, &lockstate);
5625     return (ret);
5626 }
5627 
5628 void
5629 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
5630 {
5631     RtldLockState lockstate;
5632 
5633     wlock_acquire(rtld_bind_lock, &lockstate);
5634     free_tls(tcb, tcbsize, tcbalign);
5635     lock_release(rtld_bind_lock, &lockstate);
5636 }
5637 
5638 static void
5639 object_add_name(Obj_Entry *obj, const char *name)
5640 {
5641     Name_Entry *entry;
5642     size_t len;
5643 
5644     len = strlen(name);
5645     entry = malloc(sizeof(Name_Entry) + len);
5646 
5647     if (entry != NULL) {
5648 	strcpy(entry->name, name);
5649 	STAILQ_INSERT_TAIL(&obj->names, entry, link);
5650     }
5651 }
5652 
5653 static int
5654 object_match_name(const Obj_Entry *obj, const char *name)
5655 {
5656     Name_Entry *entry;
5657 
5658     STAILQ_FOREACH(entry, &obj->names, link) {
5659 	if (strcmp(name, entry->name) == 0)
5660 	    return (1);
5661     }
5662     return (0);
5663 }
5664 
5665 static Obj_Entry *
5666 locate_dependency(const Obj_Entry *obj, const char *name)
5667 {
5668     const Objlist_Entry *entry;
5669     const Needed_Entry *needed;
5670 
5671     STAILQ_FOREACH(entry, &list_main, link) {
5672 	if (object_match_name(entry->obj, name))
5673 	    return (entry->obj);
5674     }
5675 
5676     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
5677 	if (strcmp(obj->strtab + needed->name, name) == 0 ||
5678 	  (needed->obj != NULL && object_match_name(needed->obj, name))) {
5679 	    /*
5680 	     * If there is DT_NEEDED for the name we are looking for,
5681 	     * we are all set.  Note that object might not be found if
5682 	     * dependency was not loaded yet, so the function can
5683 	     * return NULL here.  This is expected and handled
5684 	     * properly by the caller.
5685 	     */
5686 	    return (needed->obj);
5687 	}
5688     }
5689     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
5690 	obj->path, name);
5691     rtld_die();
5692 }
5693 
5694 static int
5695 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
5696     const Elf_Vernaux *vna)
5697 {
5698     const Elf_Verdef *vd;
5699     const char *vername;
5700 
5701     vername = refobj->strtab + vna->vna_name;
5702     vd = depobj->verdef;
5703     if (vd == NULL) {
5704 	_rtld_error("%s: version %s required by %s not defined",
5705 	    depobj->path, vername, refobj->path);
5706 	return (-1);
5707     }
5708     for (;;) {
5709 	if (vd->vd_version != VER_DEF_CURRENT) {
5710 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5711 		depobj->path, vd->vd_version);
5712 	    return (-1);
5713 	}
5714 	if (vna->vna_hash == vd->vd_hash) {
5715 	    const Elf_Verdaux *aux = (const Elf_Verdaux *)
5716 		((const char *)vd + vd->vd_aux);
5717 	    if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
5718 		return (0);
5719 	}
5720 	if (vd->vd_next == 0)
5721 	    break;
5722 	vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5723     }
5724     if (vna->vna_flags & VER_FLG_WEAK)
5725 	return (0);
5726     _rtld_error("%s: version %s required by %s not found",
5727 	depobj->path, vername, refobj->path);
5728     return (-1);
5729 }
5730 
5731 static int
5732 rtld_verify_object_versions(Obj_Entry *obj)
5733 {
5734     const Elf_Verneed *vn;
5735     const Elf_Verdef  *vd;
5736     const Elf_Verdaux *vda;
5737     const Elf_Vernaux *vna;
5738     const Obj_Entry *depobj;
5739     int maxvernum, vernum;
5740 
5741     if (obj->ver_checked)
5742 	return (0);
5743     obj->ver_checked = true;
5744 
5745     maxvernum = 0;
5746     /*
5747      * Walk over defined and required version records and figure out
5748      * max index used by any of them. Do very basic sanity checking
5749      * while there.
5750      */
5751     vn = obj->verneed;
5752     while (vn != NULL) {
5753 	if (vn->vn_version != VER_NEED_CURRENT) {
5754 	    _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
5755 		obj->path, vn->vn_version);
5756 	    return (-1);
5757 	}
5758 	vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5759 	for (;;) {
5760 	    vernum = VER_NEED_IDX(vna->vna_other);
5761 	    if (vernum > maxvernum)
5762 		maxvernum = vernum;
5763 	    if (vna->vna_next == 0)
5764 		 break;
5765 	    vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5766 	}
5767 	if (vn->vn_next == 0)
5768 	    break;
5769 	vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5770     }
5771 
5772     vd = obj->verdef;
5773     while (vd != NULL) {
5774 	if (vd->vd_version != VER_DEF_CURRENT) {
5775 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
5776 		obj->path, vd->vd_version);
5777 	    return (-1);
5778 	}
5779 	vernum = VER_DEF_IDX(vd->vd_ndx);
5780 	if (vernum > maxvernum)
5781 		maxvernum = vernum;
5782 	if (vd->vd_next == 0)
5783 	    break;
5784 	vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5785     }
5786 
5787     if (maxvernum == 0)
5788 	return (0);
5789 
5790     /*
5791      * Store version information in array indexable by version index.
5792      * Verify that object version requirements are satisfied along the
5793      * way.
5794      */
5795     obj->vernum = maxvernum + 1;
5796     obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
5797 
5798     vd = obj->verdef;
5799     while (vd != NULL) {
5800 	if ((vd->vd_flags & VER_FLG_BASE) == 0) {
5801 	    vernum = VER_DEF_IDX(vd->vd_ndx);
5802 	    assert(vernum <= maxvernum);
5803 	    vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux);
5804 	    obj->vertab[vernum].hash = vd->vd_hash;
5805 	    obj->vertab[vernum].name = obj->strtab + vda->vda_name;
5806 	    obj->vertab[vernum].file = NULL;
5807 	    obj->vertab[vernum].flags = 0;
5808 	}
5809 	if (vd->vd_next == 0)
5810 	    break;
5811 	vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next);
5812     }
5813 
5814     vn = obj->verneed;
5815     while (vn != NULL) {
5816 	depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
5817 	if (depobj == NULL)
5818 	    return (-1);
5819 	vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux);
5820 	for (;;) {
5821 	    if (check_object_provided_version(obj, depobj, vna))
5822 		return (-1);
5823 	    vernum = VER_NEED_IDX(vna->vna_other);
5824 	    assert(vernum <= maxvernum);
5825 	    obj->vertab[vernum].hash = vna->vna_hash;
5826 	    obj->vertab[vernum].name = obj->strtab + vna->vna_name;
5827 	    obj->vertab[vernum].file = obj->strtab + vn->vn_file;
5828 	    obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
5829 		VER_INFO_HIDDEN : 0;
5830 	    if (vna->vna_next == 0)
5831 		 break;
5832 	    vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next);
5833 	}
5834 	if (vn->vn_next == 0)
5835 	    break;
5836 	vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next);
5837     }
5838     return (0);
5839 }
5840 
5841 static int
5842 rtld_verify_versions(const Objlist *objlist)
5843 {
5844     Objlist_Entry *entry;
5845     int rc;
5846 
5847     rc = 0;
5848     STAILQ_FOREACH(entry, objlist, link) {
5849 	/*
5850 	 * Skip dummy objects or objects that have their version requirements
5851 	 * already checked.
5852 	 */
5853 	if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
5854 	    continue;
5855 	if (rtld_verify_object_versions(entry->obj) == -1) {
5856 	    rc = -1;
5857 	    if (ld_tracing == NULL)
5858 		break;
5859 	}
5860     }
5861     if (rc == 0 || ld_tracing != NULL)
5862     	rc = rtld_verify_object_versions(&obj_rtld);
5863     return (rc);
5864 }
5865 
5866 const Ver_Entry *
5867 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
5868 {
5869     Elf_Versym vernum;
5870 
5871     if (obj->vertab) {
5872 	vernum = VER_NDX(obj->versyms[symnum]);
5873 	if (vernum >= obj->vernum) {
5874 	    _rtld_error("%s: symbol %s has wrong verneed value %d",
5875 		obj->path, obj->strtab + symnum, vernum);
5876 	} else if (obj->vertab[vernum].hash != 0) {
5877 	    return (&obj->vertab[vernum]);
5878 	}
5879     }
5880     return (NULL);
5881 }
5882 
5883 int
5884 _rtld_get_stack_prot(void)
5885 {
5886 
5887 	return (stack_prot);
5888 }
5889 
5890 int
5891 _rtld_is_dlopened(void *arg)
5892 {
5893 	Obj_Entry *obj;
5894 	RtldLockState lockstate;
5895 	int res;
5896 
5897 	rlock_acquire(rtld_bind_lock, &lockstate);
5898 	obj = dlcheck(arg);
5899 	if (obj == NULL)
5900 		obj = obj_from_addr(arg);
5901 	if (obj == NULL) {
5902 		_rtld_error("No shared object contains address");
5903 		lock_release(rtld_bind_lock, &lockstate);
5904 		return (-1);
5905 	}
5906 	res = obj->dlopened ? 1 : 0;
5907 	lock_release(rtld_bind_lock, &lockstate);
5908 	return (res);
5909 }
5910 
5911 static int
5912 obj_remap_relro(Obj_Entry *obj, int prot)
5913 {
5914 
5915 	if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size,
5916 	    prot) == -1) {
5917 		_rtld_error("%s: Cannot set relro protection to %#x: %s",
5918 		    obj->path, prot, rtld_strerror(errno));
5919 		return (-1);
5920 	}
5921 	return (0);
5922 }
5923 
5924 static int
5925 obj_disable_relro(Obj_Entry *obj)
5926 {
5927 
5928 	return (obj_remap_relro(obj, PROT_READ | PROT_WRITE));
5929 }
5930 
5931 static int
5932 obj_enforce_relro(Obj_Entry *obj)
5933 {
5934 
5935 	return (obj_remap_relro(obj, PROT_READ));
5936 }
5937 
5938 static void
5939 map_stacks_exec(RtldLockState *lockstate)
5940 {
5941 	void (*thr_map_stacks_exec)(void);
5942 
5943 	if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
5944 		return;
5945 	thr_map_stacks_exec = (void (*)(void))(uintptr_t)
5946 	    get_program_var_addr("__pthread_map_stacks_exec", lockstate);
5947 	if (thr_map_stacks_exec != NULL) {
5948 		stack_prot |= PROT_EXEC;
5949 		thr_map_stacks_exec();
5950 	}
5951 }
5952 
5953 static void
5954 distribute_static_tls(Objlist *list, RtldLockState *lockstate)
5955 {
5956 	Objlist_Entry *elm;
5957 	Obj_Entry *obj;
5958 	void (*distrib)(size_t, void *, size_t, size_t);
5959 
5960 	distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t)
5961 	    get_program_var_addr("__pthread_distribute_static_tls", lockstate);
5962 	if (distrib == NULL)
5963 		return;
5964 	STAILQ_FOREACH(elm, list, link) {
5965 		obj = elm->obj;
5966 		if (obj->marker || !obj->tls_static || obj->static_tls_copied)
5967 			continue;
5968 		lock_release(rtld_bind_lock, lockstate);
5969 		distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize,
5970 		    obj->tlssize);
5971 		wlock_acquire(rtld_bind_lock, lockstate);
5972 		obj->static_tls_copied = true;
5973 	}
5974 }
5975 
5976 void
5977 symlook_init(SymLook *dst, const char *name)
5978 {
5979 
5980 	bzero(dst, sizeof(*dst));
5981 	dst->name = name;
5982 	dst->hash = elf_hash(name);
5983 	dst->hash_gnu = gnu_hash(name);
5984 }
5985 
5986 static void
5987 symlook_init_from_req(SymLook *dst, const SymLook *src)
5988 {
5989 
5990 	dst->name = src->name;
5991 	dst->hash = src->hash;
5992 	dst->hash_gnu = src->hash_gnu;
5993 	dst->ventry = src->ventry;
5994 	dst->flags = src->flags;
5995 	dst->defobj_out = NULL;
5996 	dst->sym_out = NULL;
5997 	dst->lockstate = src->lockstate;
5998 }
5999 
6000 static int
6001 open_binary_fd(const char *argv0, bool search_in_path,
6002     const char **binpath_res)
6003 {
6004 	char *binpath, *pathenv, *pe, *res1;
6005 	const char *res;
6006 	int fd;
6007 
6008 	binpath = NULL;
6009 	res = NULL;
6010 	if (search_in_path && strchr(argv0, '/') == NULL) {
6011 		binpath = xmalloc(PATH_MAX);
6012 		pathenv = getenv("PATH");
6013 		if (pathenv == NULL) {
6014 			_rtld_error("-p and no PATH environment variable");
6015 			rtld_die();
6016 		}
6017 		pathenv = strdup(pathenv);
6018 		if (pathenv == NULL) {
6019 			_rtld_error("Cannot allocate memory");
6020 			rtld_die();
6021 		}
6022 		fd = -1;
6023 		errno = ENOENT;
6024 		while ((pe = strsep(&pathenv, ":")) != NULL) {
6025 			if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX)
6026 				continue;
6027 			if (binpath[0] != '\0' &&
6028 			    strlcat(binpath, "/", PATH_MAX) >= PATH_MAX)
6029 				continue;
6030 			if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX)
6031 				continue;
6032 			fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY);
6033 			if (fd != -1 || errno != ENOENT) {
6034 				res = binpath;
6035 				break;
6036 			}
6037 		}
6038 		free(pathenv);
6039 	} else {
6040 		fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY);
6041 		res = argv0;
6042 	}
6043 
6044 	if (fd == -1) {
6045 		_rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno));
6046 		rtld_die();
6047 	}
6048 	if (res != NULL && res[0] != '/') {
6049 		res1 = xmalloc(PATH_MAX);
6050 		if (realpath(res, res1) != NULL) {
6051 			if (res != argv0)
6052 				free(__DECONST(char *, res));
6053 			res = res1;
6054 		} else {
6055 			free(res1);
6056 		}
6057 	}
6058 	*binpath_res = res;
6059 	return (fd);
6060 }
6061 
6062 /*
6063  * Parse a set of command-line arguments.
6064  */
6065 static int
6066 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp,
6067     const char **argv0, bool *dir_ignore)
6068 {
6069 	const char *arg;
6070 	char machine[64];
6071 	size_t sz;
6072 	int arglen, fd, i, j, mib[2];
6073 	char opt;
6074 	bool seen_b, seen_f;
6075 
6076 	dbg("Parsing command-line arguments");
6077 	*use_pathp = false;
6078 	*fdp = -1;
6079 	*dir_ignore = false;
6080 	seen_b = seen_f = false;
6081 
6082 	for (i = 1; i < argc; i++ ) {
6083 		arg = argv[i];
6084 		dbg("argv[%d]: '%s'", i, arg);
6085 
6086 		/*
6087 		 * rtld arguments end with an explicit "--" or with the first
6088 		 * non-prefixed argument.
6089 		 */
6090 		if (strcmp(arg, "--") == 0) {
6091 			i++;
6092 			break;
6093 		}
6094 		if (arg[0] != '-')
6095 			break;
6096 
6097 		/*
6098 		 * All other arguments are single-character options that can
6099 		 * be combined, so we need to search through `arg` for them.
6100 		 */
6101 		arglen = strlen(arg);
6102 		for (j = 1; j < arglen; j++) {
6103 			opt = arg[j];
6104 			if (opt == 'h') {
6105 				print_usage(argv[0]);
6106 				_exit(0);
6107 			} else if (opt == 'b') {
6108 				if (seen_f) {
6109 					_rtld_error("Both -b and -f specified");
6110 					rtld_die();
6111 				}
6112 				if (j != arglen - 1) {
6113 					_rtld_error("Invalid options: %s", arg);
6114 					rtld_die();
6115 				}
6116 				i++;
6117 				*argv0 = argv[i];
6118 				seen_b = true;
6119 				break;
6120 			} else if (opt == 'd') {
6121 				*dir_ignore = true;
6122 			} else if (opt == 'f') {
6123 				if (seen_b) {
6124 					_rtld_error("Both -b and -f specified");
6125 					rtld_die();
6126 				}
6127 
6128 				/*
6129 				 * -f XX can be used to specify a
6130 				 * descriptor for the binary named at
6131 				 * the command line (i.e., the later
6132 				 * argument will specify the process
6133 				 * name but the descriptor is what
6134 				 * will actually be executed).
6135 				 *
6136 				 * -f must be the last option in the
6137 				 * group, e.g., -abcf <fd>.
6138 				 */
6139 				if (j != arglen - 1) {
6140 					_rtld_error("Invalid options: %s", arg);
6141 					rtld_die();
6142 				}
6143 				i++;
6144 				fd = parse_integer(argv[i]);
6145 				if (fd == -1) {
6146 					_rtld_error(
6147 					    "Invalid file descriptor: '%s'",
6148 					    argv[i]);
6149 					rtld_die();
6150 				}
6151 				*fdp = fd;
6152 				seen_f = true;
6153 				break;
6154 			} else if (opt == 'p') {
6155 				*use_pathp = true;
6156 			} else if (opt == 'u') {
6157 				trust = false;
6158 			} else if (opt == 'v') {
6159 				machine[0] = '\0';
6160 				mib[0] = CTL_HW;
6161 				mib[1] = HW_MACHINE;
6162 				sz = sizeof(machine);
6163 				sysctl(mib, nitems(mib), machine, &sz, NULL, 0);
6164 				ld_elf_hints_path = ld_get_env_var(
6165 				    LD_ELF_HINTS_PATH);
6166 				set_ld_elf_hints_path();
6167 				rtld_printf(
6168 				    "FreeBSD ld-elf.so.1 %s\n"
6169 				    "FreeBSD_version %d\n"
6170 				    "Default lib path %s\n"
6171 				    "Hints lib path %s\n"
6172 				    "Env prefix %s\n"
6173 				    "Default hint file %s\n"
6174 				    "Hint file %s\n"
6175 				    "libmap file %s\n"
6176 				    "Optional static TLS size %zd bytes\n",
6177 				    machine,
6178 				    __FreeBSD_version, ld_standard_library_path,
6179 				    gethints(false),
6180 				    ld_env_prefix, ld_elf_hints_default,
6181 				    ld_elf_hints_path,
6182 				    ld_path_libmap_conf,
6183 				    ld_static_tls_extra);
6184 				_exit(0);
6185 			} else {
6186 				_rtld_error("Invalid argument: '%s'", arg);
6187 				print_usage(argv[0]);
6188 				rtld_die();
6189 			}
6190 		}
6191 	}
6192 
6193 	if (!seen_b)
6194 		*argv0 = argv[i];
6195 	return (i);
6196 }
6197 
6198 /*
6199  * Parse a file descriptor number without pulling in more of libc (e.g. atoi).
6200  */
6201 static int
6202 parse_integer(const char *str)
6203 {
6204 	static const int RADIX = 10;  /* XXXJA: possibly support hex? */
6205 	const char *orig;
6206 	int n;
6207 	char c;
6208 
6209 	orig = str;
6210 	n = 0;
6211 	for (c = *str; c != '\0'; c = *++str) {
6212 		if (c < '0' || c > '9')
6213 			return (-1);
6214 
6215 		n *= RADIX;
6216 		n += c - '0';
6217 	}
6218 
6219 	/* Make sure we actually parsed something. */
6220 	if (str == orig)
6221 		return (-1);
6222 	return (n);
6223 }
6224 
6225 static void
6226 print_usage(const char *argv0)
6227 {
6228 
6229 	rtld_printf(
6230 	    "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n"
6231 	    "\n"
6232 	    "Options:\n"
6233 	    "  -h        Display this help message\n"
6234 	    "  -b <exe>  Execute <exe> instead of <binary>, arg0 is <binary>\n"
6235 	    "  -d        Ignore lack of exec permissions for the binary\n"
6236 	    "  -f <FD>   Execute <FD> instead of searching for <binary>\n"
6237 	    "  -p        Search in PATH for named binary\n"
6238 	    "  -u        Ignore LD_ environment variables\n"
6239 	    "  -v        Display identification information\n"
6240 	    "  --        End of RTLD options\n"
6241 	    "  <binary>  Name of process to execute\n"
6242 	    "  <args>    Arguments to the executed process\n", argv0);
6243 }
6244 
6245 #define	AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt }
6246 static const struct auxfmt {
6247 	const char *name;
6248 	const char *fmt;
6249 } auxfmts[] = {
6250 	AUXFMT(AT_NULL, NULL),
6251 	AUXFMT(AT_IGNORE, NULL),
6252 	AUXFMT(AT_EXECFD, "%ld"),
6253 	AUXFMT(AT_PHDR, "%p"),
6254 	AUXFMT(AT_PHENT, "%lu"),
6255 	AUXFMT(AT_PHNUM, "%lu"),
6256 	AUXFMT(AT_PAGESZ, "%lu"),
6257 	AUXFMT(AT_BASE, "%#lx"),
6258 	AUXFMT(AT_FLAGS, "%#lx"),
6259 	AUXFMT(AT_ENTRY, "%p"),
6260 	AUXFMT(AT_NOTELF, NULL),
6261 	AUXFMT(AT_UID, "%ld"),
6262 	AUXFMT(AT_EUID, "%ld"),
6263 	AUXFMT(AT_GID, "%ld"),
6264 	AUXFMT(AT_EGID, "%ld"),
6265 	AUXFMT(AT_EXECPATH, "%s"),
6266 	AUXFMT(AT_CANARY, "%p"),
6267 	AUXFMT(AT_CANARYLEN, "%lu"),
6268 	AUXFMT(AT_OSRELDATE, "%lu"),
6269 	AUXFMT(AT_NCPUS, "%lu"),
6270 	AUXFMT(AT_PAGESIZES, "%p"),
6271 	AUXFMT(AT_PAGESIZESLEN, "%lu"),
6272 	AUXFMT(AT_TIMEKEEP, "%p"),
6273 	AUXFMT(AT_STACKPROT, "%#lx"),
6274 	AUXFMT(AT_EHDRFLAGS, "%#lx"),
6275 	AUXFMT(AT_HWCAP, "%#lx"),
6276 	AUXFMT(AT_HWCAP2, "%#lx"),
6277 	AUXFMT(AT_BSDFLAGS, "%#lx"),
6278 	AUXFMT(AT_ARGC, "%lu"),
6279 	AUXFMT(AT_ARGV, "%p"),
6280 	AUXFMT(AT_ENVC, "%p"),
6281 	AUXFMT(AT_ENVV, "%p"),
6282 	AUXFMT(AT_PS_STRINGS, "%p"),
6283 	AUXFMT(AT_FXRNG, "%p"),
6284 	AUXFMT(AT_KPRELOAD, "%p"),
6285 	AUXFMT(AT_USRSTACKBASE, "%#lx"),
6286 	AUXFMT(AT_USRSTACKLIM, "%#lx"),
6287 };
6288 
6289 static bool
6290 is_ptr_fmt(const char *fmt)
6291 {
6292 	char last;
6293 
6294 	last = fmt[strlen(fmt) - 1];
6295 	return (last == 'p' || last == 's');
6296 }
6297 
6298 static void
6299 dump_auxv(Elf_Auxinfo **aux_info)
6300 {
6301 	Elf_Auxinfo *auxp;
6302 	const struct auxfmt *fmt;
6303 	int i;
6304 
6305 	for (i = 0; i < AT_COUNT; i++) {
6306 		auxp = aux_info[i];
6307 		if (auxp == NULL)
6308 			continue;
6309 		fmt = &auxfmts[i];
6310 		if (fmt->fmt == NULL)
6311 			continue;
6312 		rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name);
6313 		if (is_ptr_fmt(fmt->fmt)) {
6314 			rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6315 			    auxp->a_un.a_ptr);
6316 		} else {
6317 			rtld_fdprintfx(STDOUT_FILENO, fmt->fmt,
6318 			    auxp->a_un.a_val);
6319 		}
6320 		rtld_fdprintf(STDOUT_FILENO, "\n");
6321 	}
6322 }
6323 
6324 /*
6325  * Overrides for libc_pic-provided functions.
6326  */
6327 
6328 int
6329 __getosreldate(void)
6330 {
6331 	size_t len;
6332 	int oid[2];
6333 	int error, osrel;
6334 
6335 	if (osreldate != 0)
6336 		return (osreldate);
6337 
6338 	oid[0] = CTL_KERN;
6339 	oid[1] = KERN_OSRELDATE;
6340 	osrel = 0;
6341 	len = sizeof(osrel);
6342 	error = sysctl(oid, 2, &osrel, &len, NULL, 0);
6343 	if (error == 0 && osrel > 0 && len == sizeof(osrel))
6344 		osreldate = osrel;
6345 	return (osreldate);
6346 }
6347 const char *
6348 rtld_strerror(int errnum)
6349 {
6350 
6351 	if (errnum < 0 || errnum >= sys_nerr)
6352 		return ("Unknown error");
6353 	return (sys_errlist[errnum]);
6354 }
6355 
6356 char *
6357 getenv(const char *name)
6358 {
6359 	return (__DECONST(char *, rtld_get_env_val(environ, name,
6360 	    strlen(name))));
6361 }
6362 
6363 /* malloc */
6364 void *
6365 malloc(size_t nbytes)
6366 {
6367 
6368 	return (__crt_malloc(nbytes));
6369 }
6370 
6371 void *
6372 calloc(size_t num, size_t size)
6373 {
6374 
6375 	return (__crt_calloc(num, size));
6376 }
6377 
6378 void
6379 free(void *cp)
6380 {
6381 
6382 	__crt_free(cp);
6383 }
6384 
6385 void *
6386 realloc(void *cp, size_t nbytes)
6387 {
6388 
6389 	return (__crt_realloc(cp, nbytes));
6390 }
6391 
6392 extern int _rtld_version__FreeBSD_version __exported;
6393 int _rtld_version__FreeBSD_version = __FreeBSD_version;
6394 
6395 extern char _rtld_version_laddr_offset __exported;
6396 char _rtld_version_laddr_offset;
6397 
6398 extern char _rtld_version_dlpi_tls_data __exported;
6399 char _rtld_version_dlpi_tls_data;
6400