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