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