xref: /dragonfly/libexec/rtld-elf/rtld.c (revision 2020c8fe)
1 /*-
2  * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
3  * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
4  * Copyright 2009, 2010, 2011 Konstantin Belousov <kib@FreeBSD.ORG>.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 
30 /*
31  * Dynamic linker for ELF.
32  *
33  * John Polstra <jdp@polstra.com>.
34  */
35 
36 #ifndef __GNUC__
37 #error "GCC is needed to compile this file"
38 #endif
39 
40 #include <sys/param.h>
41 #include <sys/mount.h>
42 #include <sys/mman.h>
43 #include <sys/stat.h>
44 #include <sys/sysctl.h>
45 #include <sys/uio.h>
46 #include <sys/utsname.h>
47 #include <sys/ktrace.h>
48 #include <sys/resident.h>
49 #include <sys/tls.h>
50 
51 #include <machine/tls.h>
52 
53 #include <dlfcn.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <stdarg.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 
63 #include "debug.h"
64 #include "rtld.h"
65 #include "libmap.h"
66 #include "rtld_printf.h"
67 
68 #define PATH_RTLD	"/usr/libexec/ld-elf.so.2"
69 #define LD_ARY_CACHE	16
70 
71 /* Types. */
72 typedef void (*func_ptr_type)();
73 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
74 
75 /*
76  * Function declarations.
77  */
78 static const char *_getenv_ld(const char *id);
79 static void die(void) __dead2;
80 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
81     const Elf_Dyn **);
82 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
83 static void digest_dynamic(Obj_Entry *, int);
84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
85 static Obj_Entry *dlcheck(void *);
86 static Obj_Entry *dlopen_object(const char *name, Obj_Entry *refobj,
87     int lo_flags, int mode);
88 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
89 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
90 static bool donelist_check(DoneList *, const Obj_Entry *);
91 static void errmsg_restore(char *);
92 static char *errmsg_save(void);
93 static void *fill_search_info(const char *, size_t, void *);
94 static char *find_library(const char *, const Obj_Entry *);
95 static const char *gethints(void);
96 static void init_dag(Obj_Entry *);
97 static void init_rtld(caddr_t, Elf_Auxinfo **);
98 static void initlist_add_neededs(Needed_Entry *, Objlist *);
99 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
100 static bool is_exported(const Elf_Sym *);
101 static void linkmap_add(Obj_Entry *);
102 static void linkmap_delete(Obj_Entry *);
103 static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
104 static void unload_filtees(Obj_Entry *);
105 static int load_needed_objects(Obj_Entry *, int);
106 static int load_preload_objects(void);
107 static Obj_Entry *load_object(const char *, const Obj_Entry *, int);
108 static void map_stacks_exec(RtldLockState *);
109 static Obj_Entry *obj_from_addr(const void *);
110 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
111 static void objlist_call_init(Objlist *, RtldLockState *);
112 static void preinitialize_main_object (void);
113 static void objlist_clear(Objlist *);
114 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
115 static void objlist_init(Objlist *);
116 static void objlist_push_head(Objlist *, Obj_Entry *);
117 static void objlist_push_tail(Objlist *, Obj_Entry *);
118 static void objlist_remove(Objlist *, Obj_Entry *);
119 static void *path_enumerate(const char *, path_enum_proc, void *);
120 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState *);
121 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
122     RtldLockState *lockstate);
123 static int rtld_dirname(const char *, char *);
124 static int rtld_dirname_abs(const char *, char *);
125 static void rtld_exit(void);
126 static char *search_library_path(const char *, const char *);
127 static const void **get_program_var_addr(const char *, RtldLockState *);
128 static void set_program_var(const char *, const void *);
129 static int symlook_default(SymLook *, const Obj_Entry *refobj);
130 static int symlook_global(SymLook *, DoneList *);
131 static void symlook_init_from_req(SymLook *, const SymLook *);
132 static int symlook_list(SymLook *, const Objlist *, DoneList *);
133 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
134 static int symlook_obj1(SymLook *, const Obj_Entry *);
135 static void trace_loaded_objects(Obj_Entry *);
136 static void unlink_object(Obj_Entry *);
137 static void unload_object(Obj_Entry *);
138 static void unref_dag(Obj_Entry *);
139 static void ref_dag(Obj_Entry *);
140 static int origin_subst_one(char **, const char *, const char *,
141   const char *, char *);
142 static char *origin_subst(const char *, const char *);
143 static int  rtld_verify_versions(const Objlist *);
144 static int  rtld_verify_object_versions(Obj_Entry *);
145 static void object_add_name(Obj_Entry *, const char *);
146 static int  object_match_name(const Obj_Entry *, const char *);
147 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
148 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
149     struct dl_phdr_info *phdr_info);
150 
151 void r_debug_state(struct r_debug *, struct link_map *) __noinline;
152 
153 /*
154  * Data declarations.
155  */
156 static char *error_message;	/* Message for dlerror(), or NULL */
157 struct r_debug r_debug;		/* for GDB; */
158 static bool libmap_disable;	/* Disable libmap */
159 static bool ld_loadfltr;	/* Immediate filters processing */
160 static char *libmap_override;	/* Maps to use in addition to libmap.conf */
161 static bool trust;		/* False for setuid and setgid programs */
162 static bool dangerous_ld_env;	/* True if environment variables have been
163 				   used to affect the libraries loaded */
164 static const char *ld_bind_now;	/* Environment variable for immediate binding */
165 static const char *ld_debug;	/* Environment variable for debugging */
166 static const char *ld_library_path; /* Environment variable for search path */
167 static char *ld_preload;	/* Environment variable for libraries to
168 				   load first */
169 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */
170 static const char *ld_tracing;	/* Called from ldd to print libs */
171 static const char *ld_utrace;	/* Use utrace() to log events. */
172 static int (*rtld_functrace)(   /* Optional function call tracing hook */
173 	const char *caller_obj,
174 	const char *callee_obj,
175 	const char *callee_func,
176 	void *stack);
177 static const Obj_Entry *rtld_functrace_obj;	/* Object thereof */
178 static Obj_Entry *obj_list;	/* Head of linked list of shared objects */
179 static Obj_Entry **obj_tail;	/* Link field of last object in list */
180 static Obj_Entry **preload_tail;
181 static Obj_Entry *obj_main;	/* The main program shared object */
182 static Obj_Entry obj_rtld;	/* The dynamic linker shared object */
183 static unsigned int obj_count;	/* Number of objects in obj_list */
184 static unsigned int obj_loads;	/* Number of objects in obj_list */
185 
186 static int	ld_resident;	/* Non-zero if resident */
187 static const char *ld_ary[LD_ARY_CACHE];
188 static int	ld_index;
189 static Objlist initlist;
190 
191 static Objlist list_global =	/* Objects dlopened with RTLD_GLOBAL */
192   STAILQ_HEAD_INITIALIZER(list_global);
193 static Objlist list_main =	/* Objects loaded at program startup */
194   STAILQ_HEAD_INITIALIZER(list_main);
195 static Objlist list_fini =	/* Objects needing fini() calls */
196   STAILQ_HEAD_INITIALIZER(list_fini);
197 
198 static Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
199 
200 #define GDB_STATE(s,m)	r_debug.r_state = s; r_debug_state(&r_debug,m);
201 
202 extern Elf_Dyn _DYNAMIC;
203 #pragma weak _DYNAMIC
204 #ifndef RTLD_IS_DYNAMIC
205 #define	RTLD_IS_DYNAMIC()	(&_DYNAMIC != NULL)
206 #endif
207 
208 #ifdef ENABLE_OSRELDATE
209 int osreldate;
210 #endif
211 
212 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
213 static int max_stack_flags;
214 
215 /*
216  * These are the functions the dynamic linker exports to application
217  * programs.  They are the only symbols the dynamic linker is willing
218  * to export from itself.
219  */
220 static func_ptr_type exports[] = {
221     (func_ptr_type) &_rtld_error,
222     (func_ptr_type) &dlclose,
223     (func_ptr_type) &dlerror,
224     (func_ptr_type) &dlopen,
225     (func_ptr_type) &dlfunc,
226     (func_ptr_type) &dlsym,
227     (func_ptr_type) &dlvsym,
228     (func_ptr_type) &dladdr,
229     (func_ptr_type) &dlinfo,
230     (func_ptr_type) &dl_iterate_phdr,
231 #ifdef __i386__
232     (func_ptr_type) &___tls_get_addr,
233 #endif
234     (func_ptr_type) &__tls_get_addr,
235     (func_ptr_type) &__tls_get_addr_tcb,
236     (func_ptr_type) &_rtld_allocate_tls,
237     (func_ptr_type) &_rtld_free_tls,
238     (func_ptr_type) &_rtld_call_init,
239     (func_ptr_type) &_rtld_thread_init,
240     (func_ptr_type) &_rtld_addr_phdr,
241     (func_ptr_type) &_rtld_get_stack_prot,
242     NULL
243 };
244 
245 /*
246  * Global declarations normally provided by crt1.  The dynamic linker is
247  * not built with crt1, so we have to provide them ourselves.
248  */
249 char *__progname;
250 char **environ;
251 
252 /*
253  * Globals passed as arguments to .init_array and .preinit_array functions
254  */
255 
256 int glac;
257 char **glav;
258 
259 /*
260  * Globals to control TLS allocation.
261  */
262 size_t tls_last_offset;		/* Static TLS offset of last module */
263 size_t tls_last_size;		/* Static TLS size of last module */
264 size_t tls_static_space;	/* Static TLS space allocated */
265 int tls_dtv_generation = 1;	/* Used to detect when dtv size changes  */
266 int tls_max_index = 1;		/* Largest module index allocated */
267 
268 /*
269  * Fill in a DoneList with an allocation large enough to hold all of
270  * the currently-loaded objects.  Keep this as a macro since it calls
271  * alloca and we want that to occur within the scope of the caller.
272  */
273 #define donelist_init(dlp)					\
274     ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),	\
275     assert((dlp)->objs != NULL),				\
276     (dlp)->num_alloc = obj_count,				\
277     (dlp)->num_used = 0)
278 
279 #define	UTRACE_DLOPEN_START		1
280 #define	UTRACE_DLOPEN_STOP		2
281 #define	UTRACE_DLCLOSE_START		3
282 #define	UTRACE_DLCLOSE_STOP		4
283 #define	UTRACE_LOAD_OBJECT		5
284 #define	UTRACE_UNLOAD_OBJECT		6
285 #define	UTRACE_ADD_RUNDEP		7
286 #define	UTRACE_PRELOAD_FINISHED		8
287 #define	UTRACE_INIT_CALL		9
288 #define	UTRACE_FINI_CALL		10
289 
290 struct utrace_rtld {
291 	char sig[4];			/* 'RTLD' */
292 	int event;
293 	void *handle;
294 	void *mapbase;			/* Used for 'parent' and 'init/fini' */
295 	size_t mapsize;
296 	int refcnt;			/* Used for 'mode' */
297 	char name[MAXPATHLEN];
298 };
299 
300 #define	LD_UTRACE(e, h, mb, ms, r, n) do {			\
301 	if (ld_utrace != NULL)					\
302 		ld_utrace_log(e, h, mb, ms, r, n);		\
303 } while (0)
304 
305 static void
306 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
307     int refcnt, const char *name)
308 {
309 	struct utrace_rtld ut;
310 
311 	ut.sig[0] = 'R';
312 	ut.sig[1] = 'T';
313 	ut.sig[2] = 'L';
314 	ut.sig[3] = 'D';
315 	ut.event = event;
316 	ut.handle = handle;
317 	ut.mapbase = mapbase;
318 	ut.mapsize = mapsize;
319 	ut.refcnt = refcnt;
320 	bzero(ut.name, sizeof(ut.name));
321 	if (name)
322 		strlcpy(ut.name, name, sizeof(ut.name));
323 	utrace(&ut, sizeof(ut));
324 }
325 
326 /*
327  * Main entry point for dynamic linking.  The first argument is the
328  * stack pointer.  The stack is expected to be laid out as described
329  * in the SVR4 ABI specification, Intel 386 Processor Supplement.
330  * Specifically, the stack pointer points to a word containing
331  * ARGC.  Following that in the stack is a null-terminated sequence
332  * of pointers to argument strings.  Then comes a null-terminated
333  * sequence of pointers to environment strings.  Finally, there is a
334  * sequence of "auxiliary vector" entries.
335  *
336  * The second argument points to a place to store the dynamic linker's
337  * exit procedure pointer and the third to a place to store the main
338  * program's object.
339  *
340  * The return value is the main program's entry point.
341  */
342 func_ptr_type
343 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
344 {
345     Elf_Auxinfo *aux_info[AT_COUNT];
346     int i;
347     int argc;
348     char **argv;
349     char **env;
350     Elf_Auxinfo *aux;
351     Elf_Auxinfo *auxp;
352     const char *argv0;
353     Objlist_Entry *entry;
354     Obj_Entry *obj;
355 
356     /* marino: DO NOT MOVE THESE VARIABLES TO _rtld
357              Obj_Entry **preload_tail;
358              Objlist initlist;
359        from global to here.  It will break the DWARF2 unwind scheme.
360        The system compilers were unaffected, but not gcc 4.6
361     */
362 
363     /*
364      * On entry, the dynamic linker itself has not been relocated yet.
365      * Be very careful not to reference any global data until after
366      * init_rtld has returned.  It is OK to reference file-scope statics
367      * and string constants, and to call static and global functions.
368      */
369 
370     /* Find the auxiliary vector on the stack. */
371     argc = *sp++;
372     argv = (char **) sp;
373     sp += argc + 1;	/* Skip over arguments and NULL terminator */
374     env = (char **) sp;
375 
376     /*
377      * If we aren't already resident we have to dig out some more info.
378      * Note that auxinfo does not exist when we are resident.
379      *
380      * I'm not sure about the ld_resident check.  It seems to read zero
381      * prior to relocation, which is what we want.  When running from a
382      * resident copy everything will be relocated so we are definitely
383      * good there.
384      */
385     if (ld_resident == 0)  {
386 	while (*sp++ != 0)	/* Skip over environment, and NULL terminator */
387 	    ;
388 	aux = (Elf_Auxinfo *) sp;
389 
390 	/* Digest the auxiliary vector. */
391 	for (i = 0;  i < AT_COUNT;  i++)
392 	    aux_info[i] = NULL;
393 	for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
394 	    if (auxp->a_type < AT_COUNT)
395 		aux_info[auxp->a_type] = auxp;
396 	}
397 
398 	/* Initialize and relocate ourselves. */
399 	assert(aux_info[AT_BASE] != NULL);
400 	init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
401     }
402 
403     ld_index = 0;	/* don't use old env cache in case we are resident */
404     __progname = obj_rtld.path;
405     argv0 = argv[0] != NULL ? argv[0] : "(null)";
406     environ = env;
407     glac = argc;
408     glav = argv;
409 
410     trust = !issetugid();
411 
412     ld_bind_now = _getenv_ld("LD_BIND_NOW");
413     /*
414      * If the process is tainted, then we un-set the dangerous environment
415      * variables.  The process will be marked as tainted until setuid(2)
416      * is called.  If any child process calls setuid(2) we do not want any
417      * future processes to honor the potentially un-safe variables.
418      */
419     if (!trust) {
420 	if (   unsetenv("LD_DEBUG")
421 	    || unsetenv("LD_PRELOAD")
422 	    || unsetenv("LD_LIBRARY_PATH")
423 	    || unsetenv("LD_ELF_HINTS_PATH")
424 	    || unsetenv("LD_LIBMAP")
425 	    || unsetenv("LD_LIBMAP_DISABLE")
426 	    || unsetenv("LD_LOADFLTR")
427 	) {
428 	    _rtld_error("environment corrupt; aborting");
429 	    die();
430 	}
431     }
432     ld_debug = _getenv_ld("LD_DEBUG");
433     libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
434     libmap_override = (char *)_getenv_ld("LD_LIBMAP");
435     ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
436     ld_preload = (char *)_getenv_ld("LD_PRELOAD");
437     ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
438     ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
439     dangerous_ld_env = (ld_library_path != NULL)
440 			|| (ld_preload != NULL)
441 			|| (ld_elf_hints_path != NULL)
442 			|| ld_loadfltr
443 			|| (libmap_override != NULL)
444 			|| libmap_disable
445 			;
446     ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
447     ld_utrace = _getenv_ld("LD_UTRACE");
448 
449     if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
450 	ld_elf_hints_path = _PATH_ELF_HINTS;
451 
452     if (ld_debug != NULL && *ld_debug != '\0')
453 	debug = 1;
454     dbg("%s is initialized, base address = %p", __progname,
455 	(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
456     dbg("RTLD dynamic = %p", obj_rtld.dynamic);
457     dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
458 
459     dbg("initializing thread locks");
460     lockdflt_init();
461 
462     /*
463      * If we are resident we can skip work that we have already done.
464      * Note that the stack is reset and there is no Elf_Auxinfo
465      * when running from a resident image, and the static globals setup
466      * between here and resident_skip will have already been setup.
467      */
468     if (ld_resident)
469 	goto resident_skip1;
470 
471     /*
472      * Load the main program, or process its program header if it is
473      * already loaded.
474      */
475     if (aux_info[AT_EXECFD] != NULL) {	/* Load the main program. */
476 	int fd = aux_info[AT_EXECFD]->a_un.a_val;
477 	dbg("loading main program");
478 	obj_main = map_object(fd, argv0, NULL);
479 	close(fd);
480 	if (obj_main == NULL)
481 	    die();
482 	max_stack_flags = obj->stack_flags;
483     } else {				/* Main program already loaded. */
484 	const Elf_Phdr *phdr;
485 	int phnum;
486 	caddr_t entry;
487 
488 	dbg("processing main program's program header");
489 	assert(aux_info[AT_PHDR] != NULL);
490 	phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
491 	assert(aux_info[AT_PHNUM] != NULL);
492 	phnum = aux_info[AT_PHNUM]->a_un.a_val;
493 	assert(aux_info[AT_PHENT] != NULL);
494 	assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
495 	assert(aux_info[AT_ENTRY] != NULL);
496 	entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
497 	if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
498 	    die();
499     }
500 
501     char buf[MAXPATHLEN];
502     if (aux_info[AT_EXECPATH] != 0) {
503 	char *kexecpath;
504 
505 	kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
506 	dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
507 	if (kexecpath[0] == '/')
508 		obj_main->path = kexecpath;
509 	else if (getcwd(buf, sizeof(buf)) == NULL ||
510 		strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
511 		strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
512 		obj_main->path = xstrdup(argv0);
513 	else
514 		obj_main->path = xstrdup(buf);
515     } else {
516 	char resolved[MAXPATHLEN];
517 	dbg("No AT_EXECPATH");
518 	if (argv0[0] == '/') {
519 		if (realpath(argv0, resolved) != NULL)
520 			obj_main->path = xstrdup(resolved);
521 		else
522 			obj_main->path = xstrdup(argv0);
523 	} else {
524 		if (getcwd(buf, sizeof(buf)) != NULL
525 		    && strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
526 		    && strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
527 		    && access(buf, R_OK) == 0
528 		    && realpath(buf, resolved) != NULL)
529 			obj_main->path = xstrdup(resolved);
530 		else
531 			obj_main->path = xstrdup(argv0);
532 	}
533     }
534     dbg("obj_main path %s", obj_main->path);
535     obj_main->mainprog = true;
536 
537     if (aux_info[AT_STACKPROT] != NULL &&
538       aux_info[AT_STACKPROT]->a_un.a_val != 0)
539 	    stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
540 
541     /*
542      * Get the actual dynamic linker pathname from the executable if
543      * possible.  (It should always be possible.)  That ensures that
544      * gdb will find the right dynamic linker even if a non-standard
545      * one is being used.
546      */
547     if (obj_main->interp != NULL &&
548       strcmp(obj_main->interp, obj_rtld.path) != 0) {
549 	free(obj_rtld.path);
550 	obj_rtld.path = xstrdup(obj_main->interp);
551 	__progname = obj_rtld.path;
552     }
553 
554     digest_dynamic(obj_main, 0);
555 
556     linkmap_add(obj_main);
557     linkmap_add(&obj_rtld);
558 
559     /* Link the main program into the list of objects. */
560     *obj_tail = obj_main;
561     obj_tail = &obj_main->next;
562     obj_count++;
563     obj_loads++;
564     /* Make sure we don't call the main program's init and fini functions. */
565     obj_main->init = obj_main->fini = (Elf_Addr)NULL;
566     obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
567 
568     /* Initialize a fake symbol for resolving undefined weak references. */
569     sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
570     sym_zero.st_shndx = SHN_UNDEF;
571     sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
572 
573     if (!libmap_disable)
574         libmap_disable = (bool)lm_init(libmap_override);
575 
576     dbg("loading LD_PRELOAD libraries");
577     if (load_preload_objects() == -1)
578 	die();
579     preload_tail = obj_tail;
580 
581     dbg("loading needed objects");
582     if (load_needed_objects(obj_main, 0) == -1)
583 	die();
584 
585     /* Make a list of all objects loaded at startup. */
586     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
587 	objlist_push_tail(&list_main, obj);
588 	obj->refcount++;
589     }
590 
591     dbg("checking for required versions");
592     if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
593 	die();
594 
595 resident_skip1:
596 
597     if (ld_tracing) {		/* We're done */
598 	trace_loaded_objects(obj_main);
599 	exit(0);
600     }
601 
602     if (ld_resident)		/* XXX clean this up! */
603 	goto resident_skip2;
604 
605     if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
606        dump_relocations(obj_main);
607        exit (0);
608     }
609 
610     /* setup TLS for main thread */
611     dbg("initializing initial thread local storage");
612     STAILQ_FOREACH(entry, &list_main, link) {
613 	/*
614 	 * Allocate all the initial objects out of the static TLS
615 	 * block even if they didn't ask for it.
616 	 */
617 	allocate_tls_offset(entry->obj);
618     }
619 
620     tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
621 
622     /*
623      * Do not try to allocate the TLS here, let libc do it itself.
624      * (crt1 for the program will call _init_tls())
625      */
626 
627     if (relocate_objects(obj_main,
628       ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld, NULL) == -1)
629 	die();
630 
631     dbg("doing copy relocations");
632     if (do_copy_relocations(obj_main) == -1)
633 	die();
634 
635 resident_skip2:
636 
637     if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
638 	if (exec_sys_unregister(-1) < 0) {
639 	    dbg("exec_sys_unregister failed %d\n", errno);
640 	    exit(errno);
641 	}
642 	dbg("exec_sys_unregister success\n");
643 	exit(0);
644     }
645 
646     if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
647        dump_relocations(obj_main);
648        exit (0);
649     }
650 
651     dbg("initializing key program variables");
652     set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
653     set_program_var("environ", env);
654     set_program_var("__elf_aux_vector", aux);
655 
656     if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
657 	extern void resident_start(void);
658 	ld_resident = 1;
659 	if (exec_sys_register(resident_start) < 0) {
660 	    dbg("exec_sys_register failed %d\n", errno);
661 	    exit(errno);
662 	}
663 	dbg("exec_sys_register success\n");
664 	exit(0);
665     }
666 
667     /* Make a list of init functions to call. */
668     objlist_init(&initlist);
669     initlist_add_objects(obj_list, preload_tail, &initlist);
670 
671     r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
672 
673     map_stacks_exec(NULL);
674 
675     dbg("resolving ifuncs");
676     if (resolve_objects_ifunc(obj_main,
677       ld_bind_now != NULL && *ld_bind_now != '\0', NULL) == -1)
678 	die();
679 
680     /*
681      * Do NOT call the initlist here, give libc a chance to set up
682      * the initial TLS segment.  crt1 will then call _rtld_call_init().
683      */
684 
685     dbg("transferring control to program entry point = %p", obj_main->entry);
686 
687     /* Return the exit procedure and the program entry point. */
688     *exit_proc = rtld_exit;
689     *objp = obj_main;
690     return (func_ptr_type) obj_main->entry;
691 }
692 
693 /*
694  * Call the initialization list for dynamically loaded libraries.
695  * (called from crt1.c).
696  */
697 void
698 _rtld_call_init(void)
699 {
700     RtldLockState lockstate;
701     Obj_Entry *obj;
702 
703     preinitialize_main_object();
704     wlock_acquire(rtld_bind_lock, &lockstate);
705     objlist_call_init(&initlist, &lockstate);
706     objlist_clear(&initlist);
707     dbg("loading filtees");
708     for (obj = obj_list->next; obj != NULL; obj = obj->next) {
709 	if (ld_loadfltr || obj->z_loadfltr)
710 	    load_filtees(obj, 0, &lockstate);
711     }
712     lock_release(rtld_bind_lock, &lockstate);
713 }
714 
715 void *
716 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
717 {
718 	void *ptr;
719 	Elf_Addr target;
720 
721 	ptr = (void *)make_function_pointer(def, obj);
722 	target = ((Elf_Addr (*)(void))ptr)();
723 	return ((void *)target);
724 }
725 
726 Elf_Addr
727 _rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
728 {
729     const Elf_Rel *rel;
730     const Elf_Sym *def;
731     const Obj_Entry *defobj;
732     Elf_Addr *where;
733     Elf_Addr target;
734     RtldLockState lockstate;
735 
736     rlock_acquire(rtld_bind_lock, &lockstate);
737     if (sigsetjmp(lockstate.env, 0) != 0)
738 	    lock_upgrade(rtld_bind_lock, &lockstate);
739     if (obj->pltrel)
740 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
741     else
742 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
743 
744     where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
745     def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
746 	&lockstate);
747     if (def == NULL)
748 	die();
749     if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
750 	target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
751     else
752         target = (Elf_Addr)(defobj->relocbase + def->st_value);
753 
754     dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
755       defobj->strtab + def->st_name, basename(obj->path),
756       (void *)target, basename(defobj->path));
757 
758     /*
759      * If we have a function call tracing hook, and the
760      * hook would like to keep tracing this one function,
761      * prevent the relocation so we will wind up here
762      * the next time again.
763      *
764      * We don't want to functrace calls from the functracer
765      * to avoid recursive loops.
766      */
767     if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
768 	if (rtld_functrace(obj->path,
769 			   defobj->path,
770 			   defobj->strtab + def->st_name,
771 			   stack))
772 	lock_release(rtld_bind_lock, &lockstate);
773 	return target;
774     }
775 
776     /*
777      * Write the new contents for the jmpslot. Note that depending on
778      * architecture, the value which we need to return back to the
779      * lazy binding trampoline may or may not be the target
780      * address. The value returned from reloc_jmpslot() is the value
781      * that the trampoline needs.
782      */
783     target = reloc_jmpslot(where, target, defobj, obj, rel);
784     lock_release(rtld_bind_lock, &lockstate);
785     return target;
786 }
787 
788 /*
789  * Error reporting function.  Use it like printf.  If formats the message
790  * into a buffer, and sets things up so that the next call to dlerror()
791  * will return the message.
792  */
793 void
794 _rtld_error(const char *fmt, ...)
795 {
796     static char buf[512];
797     va_list ap;
798 
799     va_start(ap, fmt);
800     rtld_vsnprintf(buf, sizeof buf, fmt, ap);
801     error_message = buf;
802     va_end(ap);
803 }
804 
805 /*
806  * Return a dynamically-allocated copy of the current error message, if any.
807  */
808 static char *
809 errmsg_save(void)
810 {
811     return error_message == NULL ? NULL : xstrdup(error_message);
812 }
813 
814 /*
815  * Restore the current error message from a copy which was previously saved
816  * by errmsg_save().  The copy is freed.
817  */
818 static void
819 errmsg_restore(char *saved_msg)
820 {
821     if (saved_msg == NULL)
822 	error_message = NULL;
823     else {
824 	_rtld_error("%s", saved_msg);
825 	free(saved_msg);
826     }
827 }
828 
829 const char *
830 basename(const char *name)
831 {
832     const char *p = strrchr(name, '/');
833     return p != NULL ? p + 1 : name;
834 }
835 
836 static struct utsname uts;
837 
838 static int
839 origin_subst_one(char **res, const char *real, const char *kw, const char *subst,
840     char *may_free)
841 {
842     const char *p, *p1;
843     char *res1;
844     int subst_len;
845     int kw_len;
846 
847     res1 = *res = NULL;
848     p = real;
849     subst_len = kw_len = 0;
850     for (;;) {
851 	 p1 = strstr(p, kw);
852 	 if (p1 != NULL) {
853 	     if (subst_len == 0) {
854 		 subst_len = strlen(subst);
855 		 kw_len = strlen(kw);
856 	     }
857 	     if (*res == NULL) {
858 		 *res = xmalloc(PATH_MAX);
859 		 res1 = *res;
860 	     }
861 	     if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
862 		 _rtld_error("Substitution of %s in %s cannot be performed",
863 		     kw, real);
864 		 if (may_free != NULL)
865 		     free(may_free);
866 		 free(res);
867 		 return (false);
868 	     }
869 	     memcpy(res1, p, p1 - p);
870 	     res1 += p1 - p;
871 	     memcpy(res1, subst, subst_len);
872 	     res1 += subst_len;
873 	     p = p1 + kw_len;
874 	 } else {
875 	    if (*res == NULL) {
876 		if (may_free != NULL)
877 		    *res = may_free;
878 		else
879 		    *res = xstrdup(real);
880 		return (true);
881 	    }
882 	    *res1 = '\0';
883 	    if (may_free != NULL)
884 		free(may_free);
885 	    if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
886 		free(res);
887 		return (false);
888 	    }
889 	    return (true);
890 	 }
891     }
892 }
893 
894 static char *
895 origin_subst(const char *real, const char *origin_path)
896 {
897     char *res1, *res2, *res3, *res4;
898 
899     if (uts.sysname[0] == '\0') {
900 	if (uname(&uts) != 0) {
901 	    _rtld_error("utsname failed: %d", errno);
902 	    return (NULL);
903 	}
904     }
905     if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
906 	!origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
907 	!origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
908 	!origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
909 	    return (NULL);
910     return (res4);
911 }
912 
913 static void
914 die(void)
915 {
916     const char *msg = dlerror();
917 
918     if (msg == NULL)
919 	msg = "Fatal error";
920     rtld_fdputstr(STDERR_FILENO, msg);
921     rtld_fdputchar(STDERR_FILENO, '\n');
922     _exit(1);
923 }
924 
925 /*
926  * Process a shared object's DYNAMIC section, and save the important
927  * information in its Obj_Entry structure.
928  */
929 static void
930 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
931     const Elf_Dyn **dyn_soname)
932 {
933     const Elf_Dyn *dynp;
934     Needed_Entry **needed_tail = &obj->needed;
935     Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
936     Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
937     int plttype = DT_REL;
938 
939     *dyn_rpath = NULL;
940     *dyn_soname = NULL;
941 
942     obj->bind_now = false;
943     for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
944 	switch (dynp->d_tag) {
945 
946 	case DT_REL:
947 	    obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
948 	    break;
949 
950 	case DT_RELSZ:
951 	    obj->relsize = dynp->d_un.d_val;
952 	    break;
953 
954 	case DT_RELENT:
955 	    assert(dynp->d_un.d_val == sizeof(Elf_Rel));
956 	    break;
957 
958 	case DT_JMPREL:
959 	    obj->pltrel = (const Elf_Rel *)
960 	      (obj->relocbase + dynp->d_un.d_ptr);
961 	    break;
962 
963 	case DT_PLTRELSZ:
964 	    obj->pltrelsize = dynp->d_un.d_val;
965 	    break;
966 
967 	case DT_RELA:
968 	    obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
969 	    break;
970 
971 	case DT_RELASZ:
972 	    obj->relasize = dynp->d_un.d_val;
973 	    break;
974 
975 	case DT_RELAENT:
976 	    assert(dynp->d_un.d_val == sizeof(Elf_Rela));
977 	    break;
978 
979 	case DT_PLTREL:
980 	    plttype = dynp->d_un.d_val;
981 	    assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
982 	    break;
983 
984 	case DT_SYMTAB:
985 	    obj->symtab = (const Elf_Sym *)
986 	      (obj->relocbase + dynp->d_un.d_ptr);
987 	    break;
988 
989 	case DT_SYMENT:
990 	    assert(dynp->d_un.d_val == sizeof(Elf_Sym));
991 	    break;
992 
993 	case DT_STRTAB:
994 	    obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
995 	    break;
996 
997 	case DT_STRSZ:
998 	    obj->strsize = dynp->d_un.d_val;
999 	    break;
1000 
1001 	case DT_VERNEED:
1002 	    obj->verneed = (const Elf_Verneed *) (obj->relocbase +
1003 		dynp->d_un.d_val);
1004 	    break;
1005 
1006 	case DT_VERNEEDNUM:
1007 	    obj->verneednum = dynp->d_un.d_val;
1008 	    break;
1009 
1010 	case DT_VERDEF:
1011 	    obj->verdef = (const Elf_Verdef *) (obj->relocbase +
1012 		dynp->d_un.d_val);
1013 	    break;
1014 
1015 	case DT_VERDEFNUM:
1016 	    obj->verdefnum = dynp->d_un.d_val;
1017 	    break;
1018 
1019 	case DT_VERSYM:
1020 	    obj->versyms = (const Elf_Versym *)(obj->relocbase +
1021 		dynp->d_un.d_val);
1022 	    break;
1023 
1024 	case DT_HASH:
1025 	    {
1026 		const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
1027 		  (obj->relocbase + dynp->d_un.d_ptr);
1028 		obj->nbuckets = hashtab[0];
1029 		obj->nchains = hashtab[1];
1030 		obj->buckets = hashtab + 2;
1031 		obj->chains = obj->buckets + obj->nbuckets;
1032 	    }
1033 	    break;
1034 
1035 	case DT_NEEDED:
1036 	    if (!obj->rtld) {
1037 		Needed_Entry *nep = NEW(Needed_Entry);
1038 		nep->name = dynp->d_un.d_val;
1039 		nep->obj = NULL;
1040 		nep->next = NULL;
1041 
1042 		*needed_tail = nep;
1043 		needed_tail = &nep->next;
1044 	    }
1045 	    break;
1046 
1047 	case DT_FILTER:
1048 	    if (!obj->rtld) {
1049 		Needed_Entry *nep = NEW(Needed_Entry);
1050 		nep->name = dynp->d_un.d_val;
1051 		nep->obj = NULL;
1052 		nep->next = NULL;
1053 
1054 		*needed_filtees_tail = nep;
1055 		needed_filtees_tail = &nep->next;
1056 	    }
1057 	    break;
1058 
1059 	case DT_AUXILIARY:
1060 	    if (!obj->rtld) {
1061 		Needed_Entry *nep = NEW(Needed_Entry);
1062 		nep->name = dynp->d_un.d_val;
1063 		nep->obj = NULL;
1064 		nep->next = NULL;
1065 
1066 		*needed_aux_filtees_tail = nep;
1067 		needed_aux_filtees_tail = &nep->next;
1068 	    }
1069 	    break;
1070 
1071 	case DT_PLTGOT:
1072 	    obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
1073 	    break;
1074 
1075 	case DT_TEXTREL:
1076 	    obj->textrel = true;
1077 	    break;
1078 
1079 	case DT_SYMBOLIC:
1080 	    obj->symbolic = true;
1081 	    break;
1082 
1083 	case DT_RPATH:
1084 	case DT_RUNPATH:	/* XXX: process separately */
1085 	    /*
1086 	     * We have to wait until later to process this, because we
1087 	     * might not have gotten the address of the string table yet.
1088 	     */
1089 	    *dyn_rpath = dynp;
1090 	    break;
1091 
1092 	case DT_SONAME:
1093 	    *dyn_soname = dynp;
1094 	    break;
1095 
1096 	case DT_INIT:
1097 	    obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1098 	    break;
1099 
1100 	case DT_FINI:
1101 	    obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1102 	    break;
1103 
1104 	case DT_PREINIT_ARRAY:
1105 	    obj->preinit_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1106 	    break;
1107 
1108 	case DT_INIT_ARRAY:
1109 	    obj->init_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1110 	    break;
1111 
1112 	case DT_FINI_ARRAY:
1113 	    obj->fini_array = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
1114 	    break;
1115 
1116 	case DT_PREINIT_ARRAYSZ:
1117 	    obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1118 	    break;
1119 
1120 	case DT_INIT_ARRAYSZ:
1121 	    obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1122 	    break;
1123 
1124 	case DT_FINI_ARRAYSZ:
1125 	    obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr);
1126 	    break;
1127 
1128 	case DT_DEBUG:
1129 	    /* XXX - not implemented yet */
1130 	    if (!early)
1131 		dbg("Filling in DT_DEBUG entry");
1132 	    ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
1133 	    break;
1134 
1135 	case DT_FLAGS:
1136 		if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
1137 		    obj->z_origin = true;
1138 		if (dynp->d_un.d_val & DF_SYMBOLIC)
1139 		    obj->symbolic = true;
1140 		if (dynp->d_un.d_val & DF_TEXTREL)
1141 		    obj->textrel = true;
1142 		if (dynp->d_un.d_val & DF_BIND_NOW)
1143 		    obj->bind_now = true;
1144 		/*if (dynp->d_un.d_val & DF_STATIC_TLS)
1145 		    ;*/
1146 	    break;
1147 
1148 	case DT_FLAGS_1:
1149 		if (dynp->d_un.d_val & DF_1_NOOPEN)
1150 		    obj->z_noopen = true;
1151 		if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
1152 		    obj->z_origin = true;
1153 		/*if (dynp->d_un.d_val & DF_1_GLOBAL)
1154 		    XXX ;*/
1155 		if (dynp->d_un.d_val & DF_1_BIND_NOW)
1156 		    obj->bind_now = true;
1157 		if (dynp->d_un.d_val & DF_1_NODELETE)
1158 		    obj->z_nodelete = true;
1159 		if (dynp->d_un.d_val & DF_1_LOADFLTR)
1160 		    obj->z_loadfltr = true;
1161 	    break;
1162 
1163 	default:
1164 	    if (!early) {
1165 		dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
1166 		    (long)dynp->d_tag);
1167 	    }
1168 	    break;
1169 	}
1170     }
1171 
1172     obj->traced = false;
1173 
1174     if (plttype == DT_RELA) {
1175 	obj->pltrela = (const Elf_Rela *) obj->pltrel;
1176 	obj->pltrel = NULL;
1177 	obj->pltrelasize = obj->pltrelsize;
1178 	obj->pltrelsize = 0;
1179     }
1180 }
1181 
1182 static void
1183 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
1184     const Elf_Dyn *dyn_soname)
1185 {
1186 
1187     if (obj->z_origin && obj->origin_path == NULL) {
1188 	obj->origin_path = xmalloc(PATH_MAX);
1189 	if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
1190 	    die();
1191     }
1192 
1193     if (dyn_rpath != NULL) {
1194 	obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
1195 	if (obj->z_origin)
1196 	    obj->rpath = origin_subst(obj->rpath, obj->origin_path);
1197     }
1198 
1199     if (dyn_soname != NULL)
1200 	object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
1201 }
1202 
1203 static void
1204 digest_dynamic(Obj_Entry *obj, int early)
1205 {
1206 	const Elf_Dyn *dyn_rpath;
1207 	const Elf_Dyn *dyn_soname;
1208 
1209 	digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
1210 	digest_dynamic2(obj, dyn_rpath, dyn_soname);
1211 }
1212 
1213 /*
1214  * Process a shared object's program header.  This is used only for the
1215  * main program, when the kernel has already loaded the main program
1216  * into memory before calling the dynamic linker.  It creates and
1217  * returns an Obj_Entry structure.
1218  */
1219 static Obj_Entry *
1220 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
1221 {
1222     Obj_Entry *obj;
1223     const Elf_Phdr *phlimit = phdr + phnum;
1224     const Elf_Phdr *ph;
1225     int nsegs = 0;
1226 
1227     obj = obj_new();
1228     for (ph = phdr;  ph < phlimit;  ph++) {
1229 	if (ph->p_type != PT_PHDR)
1230 	    continue;
1231 
1232 	obj->phdr = phdr;
1233 	obj->phsize = ph->p_memsz;
1234 	obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1235 	break;
1236     }
1237 
1238     obj->stack_flags = PF_X | PF_R | PF_W;
1239 
1240     for (ph = phdr;  ph < phlimit;  ph++) {
1241 	switch (ph->p_type) {
1242 
1243 	case PT_INTERP:
1244 	    obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1245 	    break;
1246 
1247 	case PT_LOAD:
1248 	    if (nsegs == 0) {	/* First load segment */
1249 		obj->vaddrbase = trunc_page(ph->p_vaddr);
1250 		obj->mapbase = obj->vaddrbase + obj->relocbase;
1251 		obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1252 		  obj->vaddrbase;
1253 	    } else {		/* Last load segment */
1254 		obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1255 		  obj->vaddrbase;
1256 	    }
1257 	    nsegs++;
1258 	    break;
1259 
1260 	case PT_DYNAMIC:
1261 	    obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1262 	    break;
1263 
1264 	case PT_TLS:
1265 	    obj->tlsindex = 1;
1266 	    obj->tlssize = ph->p_memsz;
1267 	    obj->tlsalign = ph->p_align;
1268 	    obj->tlsinitsize = ph->p_filesz;
1269 	    obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1270 	    break;
1271 
1272 	case PT_GNU_STACK:
1273 	    obj->stack_flags = ph->p_flags;
1274 	    break;
1275 
1276 	case PT_GNU_RELRO:
1277 	    obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1278 	    obj->relro_size = round_page(ph->p_memsz);
1279 	    break;
1280 	}
1281     }
1282     if (nsegs < 1) {
1283 	_rtld_error("%s: too few PT_LOAD segments", path);
1284 	return NULL;
1285     }
1286 
1287     obj->entry = entry;
1288     return obj;
1289 }
1290 
1291 static Obj_Entry *
1292 dlcheck(void *handle)
1293 {
1294     Obj_Entry *obj;
1295 
1296     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1297 	if (obj == (Obj_Entry *) handle)
1298 	    break;
1299 
1300     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1301 	_rtld_error("Invalid shared object handle %p", handle);
1302 	return NULL;
1303     }
1304     return obj;
1305 }
1306 
1307 /*
1308  * If the given object is already in the donelist, return true.  Otherwise
1309  * add the object to the list and return false.
1310  */
1311 static bool
1312 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1313 {
1314     unsigned int i;
1315 
1316     for (i = 0;  i < dlp->num_used;  i++)
1317 	if (dlp->objs[i] == obj)
1318 	    return true;
1319     /*
1320      * Our donelist allocation should always be sufficient.  But if
1321      * our threads locking isn't working properly, more shared objects
1322      * could have been loaded since we allocated the list.  That should
1323      * never happen, but we'll handle it properly just in case it does.
1324      */
1325     if (dlp->num_used < dlp->num_alloc)
1326 	dlp->objs[dlp->num_used++] = obj;
1327     return false;
1328 }
1329 
1330 /*
1331  * Hash function for symbol table lookup.  Don't even think about changing
1332  * this.  It is specified by the System V ABI.
1333  */
1334 unsigned long
1335 elf_hash(const char *name)
1336 {
1337     const unsigned char *p = (const unsigned char *) name;
1338     unsigned long h = 0;
1339     unsigned long g;
1340 
1341     while (*p != '\0') {
1342 	h = (h << 4) + *p++;
1343 	if ((g = h & 0xf0000000) != 0)
1344 	    h ^= g >> 24;
1345 	h &= ~g;
1346     }
1347     return h;
1348 }
1349 
1350 /*
1351  * Find the library with the given name, and return its full pathname.
1352  * The returned string is dynamically allocated.  Generates an error
1353  * message and returns NULL if the library cannot be found.
1354  *
1355  * If the second argument is non-NULL, then it refers to an already-
1356  * loaded shared object, whose library search path will be searched.
1357  *
1358  * The search order is:
1359  *   LD_LIBRARY_PATH
1360  *   rpath in the referencing file
1361  *   ldconfig hints
1362  *   /usr/lib
1363  */
1364 static char *
1365 find_library(const char *xname, const Obj_Entry *refobj)
1366 {
1367     char *pathname;
1368     char *name;
1369 
1370     if (strchr(xname, '/') != NULL) {	/* Hard coded pathname */
1371 	if (xname[0] != '/' && !trust) {
1372 	    _rtld_error("Absolute pathname required for shared object \"%s\"",
1373 	      xname);
1374 	    return NULL;
1375 	}
1376 	if (refobj != NULL && refobj->z_origin)
1377 	    return origin_subst(xname, refobj->origin_path);
1378 	else
1379 	    return xstrdup(xname);
1380     }
1381 
1382     if (libmap_disable || (refobj == NULL) ||
1383 	(name = lm_find(refobj->path, xname)) == NULL)
1384 	name = (char *)xname;
1385 
1386     dbg(" Searching for \"%s\"", name);
1387 
1388     if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1389       (refobj != NULL &&
1390       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1391       (pathname = search_library_path(name, gethints())) != NULL ||
1392       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1393 	return pathname;
1394 
1395     if(refobj != NULL && refobj->path != NULL) {
1396 	_rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1397 	  name, basename(refobj->path));
1398     } else {
1399 	_rtld_error("Shared object \"%s\" not found", name);
1400     }
1401     return NULL;
1402 }
1403 
1404 /*
1405  * Given a symbol number in a referencing object, find the corresponding
1406  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1407  * no definition was found.  Returns a pointer to the Obj_Entry of the
1408  * defining object via the reference parameter DEFOBJ_OUT.
1409  */
1410 const Elf_Sym *
1411 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1412     const Obj_Entry **defobj_out, int flags, SymCache *cache,
1413     RtldLockState *lockstate)
1414 {
1415     const Elf_Sym *ref;
1416     const Elf_Sym *def;
1417     const Obj_Entry *defobj;
1418     SymLook req;
1419     const char *name;
1420     int res;
1421 
1422     /*
1423      * If we have already found this symbol, get the information from
1424      * the cache.
1425      */
1426     if (symnum >= refobj->nchains)
1427 	return NULL;	/* Bad object */
1428     if (cache != NULL && cache[symnum].sym != NULL) {
1429 	*defobj_out = cache[symnum].obj;
1430 	return cache[symnum].sym;
1431     }
1432 
1433     ref = refobj->symtab + symnum;
1434     name = refobj->strtab + ref->st_name;
1435     def = NULL;
1436     defobj = NULL;
1437 
1438     /*
1439      * We don't have to do a full scale lookup if the symbol is local.
1440      * We know it will bind to the instance in this load module; to
1441      * which we already have a pointer (ie ref). By not doing a lookup,
1442      * we not only improve performance, but it also avoids unresolvable
1443      * symbols when local symbols are not in the hash table.
1444      *
1445      * This might occur for TLS module relocations, which simply use
1446      * symbol 0.
1447      */
1448     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1449 	if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1450 	    _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1451 		symnum);
1452 	}
1453 	symlook_init(&req, name);
1454 	req.flags = flags;
1455 	req.ventry = fetch_ventry(refobj, symnum);
1456 	req.lockstate = lockstate;
1457 	res = symlook_default(&req, refobj);
1458 	if (res == 0) {
1459 	    def = req.sym_out;
1460 	    defobj = req.defobj_out;
1461 	}
1462     } else {
1463 	def = ref;
1464 	defobj = refobj;
1465     }
1466 
1467     /*
1468      * If we found no definition and the reference is weak, treat the
1469      * symbol as having the value zero.
1470      */
1471     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1472 	def = &sym_zero;
1473 	defobj = obj_main;
1474     }
1475 
1476     if (def != NULL) {
1477 	*defobj_out = defobj;
1478 	/* Record the information in the cache to avoid subsequent lookups. */
1479 	if (cache != NULL) {
1480 	    cache[symnum].sym = def;
1481 	    cache[symnum].obj = defobj;
1482 	}
1483     } else {
1484 	if (refobj != &obj_rtld)
1485 	    _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1486     }
1487     return def;
1488 }
1489 
1490 /*
1491  * Return the search path from the ldconfig hints file, reading it if
1492  * necessary.  Returns NULL if there are problems with the hints file,
1493  * or if the search path there is empty.
1494  */
1495 static const char *
1496 gethints(void)
1497 {
1498     static char *hints;
1499 
1500     if (hints == NULL) {
1501 	int fd;
1502 	struct elfhints_hdr hdr;
1503 	char *p;
1504 
1505 	/* Keep from trying again in case the hints file is bad. */
1506 	hints = "";
1507 
1508 	if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1509 	    return NULL;
1510 	if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1511 	  hdr.magic != ELFHINTS_MAGIC ||
1512 	  hdr.version != 1) {
1513 	    close(fd);
1514 	    return NULL;
1515 	}
1516 	p = xmalloc(hdr.dirlistlen + 1);
1517 	if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1518 	  read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1519 	    free(p);
1520 	    close(fd);
1521 	    return NULL;
1522 	}
1523 	hints = p;
1524 	close(fd);
1525     }
1526     return hints[0] != '\0' ? hints : NULL;
1527 }
1528 
1529 static void
1530 init_dag(Obj_Entry *root)
1531 {
1532     const Needed_Entry *needed;
1533     const Objlist_Entry *elm;
1534     DoneList donelist;
1535 
1536     if (root->dag_inited)
1537 	return;
1538     donelist_init(&donelist);
1539 
1540     /* Root object belongs to own DAG. */
1541     objlist_push_tail(&root->dldags, root);
1542     objlist_push_tail(&root->dagmembers, root);
1543     donelist_check(&donelist, root);
1544 
1545     /*
1546      * Add dependencies of root object to DAG in breadth order
1547      * by exploiting the fact that each new object get added
1548      * to the tail of the dagmembers list.
1549      */
1550     STAILQ_FOREACH(elm, &root->dagmembers, link) {
1551 	for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1552 	    if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1553 		continue;
1554 	    objlist_push_tail(&needed->obj->dldags, root);
1555 	    objlist_push_tail(&root->dagmembers, needed->obj);
1556 	}
1557     }
1558     root->dag_inited = true;
1559 }
1560 
1561 /*
1562  * Initialize the dynamic linker.  The argument is the address at which
1563  * the dynamic linker has been mapped into memory.  The primary task of
1564  * this function is to relocate the dynamic linker.
1565  */
1566 static void
1567 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1568 {
1569     Obj_Entry objtmp;	/* Temporary rtld object */
1570     const Elf_Dyn *dyn_rpath;
1571     const Elf_Dyn *dyn_soname;
1572 
1573     /*
1574      * Conjure up an Obj_Entry structure for the dynamic linker.
1575      *
1576      * The "path" member can't be initialized yet because string constants
1577      * cannot yet be accessed. Below we will set it correctly.
1578      */
1579     memset(&objtmp, 0, sizeof(objtmp));
1580     objtmp.path = NULL;
1581     objtmp.rtld = true;
1582     objtmp.mapbase = mapbase;
1583 #ifdef PIC
1584     objtmp.relocbase = mapbase;
1585 #endif
1586     if (RTLD_IS_DYNAMIC()) {
1587 	objtmp.dynamic = rtld_dynamic(&objtmp);
1588 	digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1589 	assert(objtmp.needed == NULL);
1590 	assert(!objtmp.textrel);
1591 
1592 	/*
1593 	 * Temporarily put the dynamic linker entry into the object list, so
1594 	 * that symbols can be found.
1595 	 */
1596 
1597 	relocate_objects(&objtmp, true, &objtmp, NULL);
1598     }
1599 
1600     /* Initialize the object list. */
1601     obj_tail = &obj_list;
1602 
1603     /* Now that non-local variables can be accesses, copy out obj_rtld. */
1604     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1605 
1606 #ifdef ENABLE_OSRELDATE
1607     if (aux_info[AT_OSRELDATE] != NULL)
1608 	    osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1609 #endif
1610 
1611     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1612 
1613     /* Replace the path with a dynamically allocated copy. */
1614     obj_rtld.path = xstrdup(PATH_RTLD);
1615 
1616     r_debug.r_brk = r_debug_state;
1617     r_debug.r_state = RT_CONSISTENT;
1618 }
1619 
1620 /*
1621  * Add the init functions from a needed object list (and its recursive
1622  * needed objects) to "list".  This is not used directly; it is a helper
1623  * function for initlist_add_objects().  The write lock must be held
1624  * when this function is called.
1625  */
1626 static void
1627 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1628 {
1629     /* Recursively process the successor needed objects. */
1630     if (needed->next != NULL)
1631 	initlist_add_neededs(needed->next, list);
1632 
1633     /* Process the current needed object. */
1634     if (needed->obj != NULL)
1635 	initlist_add_objects(needed->obj, &needed->obj->next, list);
1636 }
1637 
1638 /*
1639  * Scan all of the DAGs rooted in the range of objects from "obj" to
1640  * "tail" and add their init functions to "list".  This recurses over
1641  * the DAGs and ensure the proper init ordering such that each object's
1642  * needed libraries are initialized before the object itself.  At the
1643  * same time, this function adds the objects to the global finalization
1644  * list "list_fini" in the opposite order.  The write lock must be
1645  * held when this function is called.
1646  */
1647 static void
1648 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1649 {
1650     if (obj->init_scanned || obj->init_done)
1651 	return;
1652     obj->init_scanned = true;
1653 
1654     /* Recursively process the successor objects. */
1655     if (&obj->next != tail)
1656 	initlist_add_objects(obj->next, tail, list);
1657 
1658     /* Recursively process the needed objects. */
1659     if (obj->needed != NULL)
1660 	initlist_add_neededs(obj->needed, list);
1661 
1662     /* Add the object to the init list. */
1663     if (obj->init != (Elf_Addr)NULL || obj->init_array != (Elf_Addr)NULL)
1664 	objlist_push_tail(list, obj);
1665 
1666     /* Add the object to the global fini list in the reverse order. */
1667     if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1668       && !obj->on_fini_list) {
1669 	objlist_push_head(&list_fini, obj);
1670 	obj->on_fini_list = true;
1671     }
1672 }
1673 
1674 #ifndef FPTR_TARGET
1675 #define FPTR_TARGET(f)	((Elf_Addr) (f))
1676 #endif
1677 
1678 static bool
1679 is_exported(const Elf_Sym *def)
1680 {
1681     Elf_Addr value;
1682     const func_ptr_type *p;
1683 
1684     value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1685     for (p = exports;  *p != NULL;  p++)
1686 	if (FPTR_TARGET(*p) == value)
1687 	    return true;
1688     return false;
1689 }
1690 
1691 static void
1692 free_needed_filtees(Needed_Entry *n)
1693 {
1694     Needed_Entry *needed, *needed1;
1695 
1696     for (needed = n; needed != NULL; needed = needed->next) {
1697 	if (needed->obj != NULL) {
1698 	    dlclose(needed->obj);
1699 	    needed->obj = NULL;
1700 	}
1701     }
1702     for (needed = n; needed != NULL; needed = needed1) {
1703 	needed1 = needed->next;
1704 	free(needed);
1705     }
1706 }
1707 
1708 static void
1709 unload_filtees(Obj_Entry *obj)
1710 {
1711 
1712     free_needed_filtees(obj->needed_filtees);
1713     obj->needed_filtees = NULL;
1714     free_needed_filtees(obj->needed_aux_filtees);
1715     obj->needed_aux_filtees = NULL;
1716     obj->filtees_loaded = false;
1717 }
1718 
1719 static void
1720 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1721 {
1722 
1723     for (; needed != NULL; needed = needed->next) {
1724 	needed->obj = dlopen_object(obj->strtab + needed->name, obj,
1725 	  flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1726 	  RTLD_LOCAL);
1727     }
1728 }
1729 
1730 static void
1731 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1732 {
1733 
1734     lock_restart_for_upgrade(lockstate);
1735     if (!obj->filtees_loaded) {
1736 	load_filtee1(obj, obj->needed_filtees, flags);
1737 	load_filtee1(obj, obj->needed_aux_filtees, flags);
1738 	obj->filtees_loaded = true;
1739     }
1740 }
1741 
1742 static int
1743 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1744 {
1745     Obj_Entry *obj1;
1746 
1747     for (; needed != NULL; needed = needed->next) {
1748 	obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1749 	  flags & ~RTLD_LO_NOLOAD);
1750 	if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1751 	    return (-1);
1752 	if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1753 	    dbg("obj %s nodelete", obj1->path);
1754 	    init_dag(obj1);
1755 	    ref_dag(obj1);
1756 	    obj1->ref_nodel = true;
1757 	}
1758     }
1759     return (0);
1760 }
1761 
1762 /*
1763  * Given a shared object, traverse its list of needed objects, and load
1764  * each of them.  Returns 0 on success.  Generates an error message and
1765  * returns -1 on failure.
1766  */
1767 static int
1768 load_needed_objects(Obj_Entry *first, int flags)
1769 {
1770     Obj_Entry *obj;
1771 
1772     for (obj = first;  obj != NULL;  obj = obj->next) {
1773 	if (process_needed(obj, obj->needed, flags) == -1)
1774 	    return (-1);
1775     }
1776     return (0);
1777 }
1778 
1779 static int
1780 load_preload_objects(void)
1781 {
1782     char *p = ld_preload;
1783     static const char delim[] = " \t:;";
1784 
1785     if (p == NULL)
1786 	return 0;
1787 
1788     p += strspn(p, delim);
1789     while (*p != '\0') {
1790 	size_t len = strcspn(p, delim);
1791 	char savech;
1792 	Obj_Entry *obj;
1793 	SymLook req;
1794 	int res;
1795 
1796 	savech = p[len];
1797 	p[len] = '\0';
1798 	obj = load_object(p, NULL, 0);
1799 	if (obj == NULL)
1800 	    return -1;	/* XXX - cleanup */
1801 	p[len] = savech;
1802 	p += len;
1803 	p += strspn(p, delim);
1804 
1805 	/* Check for the magic tracing function */
1806 	symlook_init(&req, RTLD_FUNCTRACE);
1807 	res = symlook_obj(&req, obj);
1808 	if (res == 0) {
1809 	    rtld_functrace = (void *)(req.defobj_out->relocbase +
1810 				      req.sym_out->st_value);
1811 	    rtld_functrace_obj = req.defobj_out;
1812 	}
1813     }
1814     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1815     return 0;
1816 }
1817 
1818 /*
1819  * Load a shared object into memory, if it is not already loaded.
1820  *
1821  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1822  * on failure.
1823  */
1824 static Obj_Entry *
1825 load_object(const char *name, const Obj_Entry *refobj, int flags)
1826 {
1827     Obj_Entry *obj;
1828     int fd = -1;
1829     struct stat sb;
1830     char *path;
1831 
1832     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1833 	if (object_match_name(obj, name))
1834 	    return obj;
1835 
1836     path = find_library(name, refobj);
1837     if (path == NULL)
1838 	return NULL;
1839 
1840     /*
1841      * If we didn't find a match by pathname, open the file and check
1842      * again by device and inode.  This avoids false mismatches caused
1843      * by multiple links or ".." in pathnames.
1844      *
1845      * To avoid a race, we open the file and use fstat() rather than
1846      * using stat().
1847      */
1848     if ((fd = open(path, O_RDONLY)) == -1) {
1849 	_rtld_error("Cannot open \"%s\"", path);
1850 	free(path);
1851 	return NULL;
1852     }
1853     if (fstat(fd, &sb) == -1) {
1854 	_rtld_error("Cannot fstat \"%s\"", path);
1855 	close(fd);
1856 	free(path);
1857 	return NULL;
1858     }
1859     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1860 	if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1861 	    break;
1862     if (obj != NULL) {
1863 	object_add_name(obj, name);
1864 	free(path);
1865 	close(fd);
1866 	return obj;
1867     }
1868     if (flags & RTLD_LO_NOLOAD) {
1869 	free(path);
1870 	close(fd);
1871 	return (NULL);
1872     }
1873 
1874     /* First use of this object, so we must map it in */
1875     obj = do_load_object(fd, name, path, &sb, flags);
1876     if (obj == NULL)
1877 	free(path);
1878     close(fd);
1879 
1880     return obj;
1881 }
1882 
1883 static Obj_Entry *
1884 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1885   int flags)
1886 {
1887     Obj_Entry *obj;
1888     struct statfs fs;
1889 
1890     /*
1891      * but first, make sure that environment variables haven't been
1892      * used to circumvent the noexec flag on a filesystem.
1893      */
1894     if (dangerous_ld_env) {
1895 	if (fstatfs(fd, &fs) != 0) {
1896 	    _rtld_error("Cannot fstatfs \"%s\"", path);
1897 		return NULL;
1898 	}
1899 	if (fs.f_flags & MNT_NOEXEC) {
1900 	    _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1901 	    return NULL;
1902 	}
1903     }
1904     dbg("loading \"%s\"", path);
1905     obj = map_object(fd, path, sbp);
1906     if (obj == NULL)
1907         return NULL;
1908 
1909     object_add_name(obj, name);
1910     obj->path = path;
1911     digest_dynamic(obj, 0);
1912     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1913       RTLD_LO_DLOPEN) {
1914 	dbg("refusing to load non-loadable \"%s\"", obj->path);
1915 	_rtld_error("Cannot dlopen non-loadable %s", obj->path);
1916 	munmap(obj->mapbase, obj->mapsize);
1917 	obj_free(obj);
1918 	return (NULL);
1919     }
1920 
1921     *obj_tail = obj;
1922     obj_tail = &obj->next;
1923     obj_count++;
1924     obj_loads++;
1925     linkmap_add(obj);	/* for GDB & dlinfo() */
1926     max_stack_flags |= obj->stack_flags;
1927 
1928     dbg("  %p .. %p: %s", obj->mapbase,
1929          obj->mapbase + obj->mapsize - 1, obj->path);
1930     if (obj->textrel)
1931 	dbg("  WARNING: %s has impure text", obj->path);
1932     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1933 	obj->path);
1934 
1935     return obj;
1936 }
1937 
1938 static Obj_Entry *
1939 obj_from_addr(const void *addr)
1940 {
1941     Obj_Entry *obj;
1942 
1943     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1944 	if (addr < (void *) obj->mapbase)
1945 	    continue;
1946 	if (addr < (void *) (obj->mapbase + obj->mapsize))
1947 	    return obj;
1948     }
1949     return NULL;
1950 }
1951 
1952 /*
1953  * Call the finalization functions for each of the objects in "list"
1954  * belonging to the DAG of "root" and referenced once. If NULL "root"
1955  * is specified, every finalization function will be called regardless
1956  * of the reference count and the list elements won't be freed. All of
1957  * the objects are expected to have non-NULL fini functions.
1958  */
1959 static void
1960 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1961 {
1962     Objlist_Entry *elm;
1963     char *saved_msg;
1964     Elf_Addr *fini_addr;
1965     int index;
1966 
1967     assert(root == NULL || root->refcount == 1);
1968 
1969     /*
1970      * Preserve the current error message since a fini function might
1971      * call into the dynamic linker and overwrite it.
1972      */
1973     saved_msg = errmsg_save();
1974     do {
1975 	STAILQ_FOREACH(elm, list, link) {
1976 	    if (root != NULL && (elm->obj->refcount != 1 ||
1977 	      objlist_find(&root->dagmembers, elm->obj) == NULL))
1978 		continue;
1979 
1980 	    /* Remove object from fini list to prevent recursive invocation. */
1981 	    STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1982 	    /*
1983 	     * XXX: If a dlopen() call references an object while the
1984 	     * fini function is in progress, we might end up trying to
1985 	     * unload the referenced object in dlclose() or the object
1986 	     * won't be unloaded although its fini function has been
1987 	     * called.
1988 	     */
1989 	    lock_release(rtld_bind_lock, lockstate);
1990 
1991 	    /*
1992 	     * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.  When this
1993 	     * happens, DT_FINI_ARRAY is processed first, and it is also processed
1994 	     * backwards.  It is possible to encounter DT_FINI_ARRAY elements with
1995 	     * values of 0 or 1, but they need to be ignored.
1996 	     */
1997 	    fini_addr = (Elf_Addr *)elm->obj->fini_array;
1998 	    if (fini_addr != (Elf_Addr)NULL) {
1999 		for (index = elm->obj->fini_array_num - 1; index >= 0; index--) {
2000 		    if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2001 			dbg("DSO Array: calling fini function for %s at %p",
2002 		            elm->obj->path, (void *)fini_addr[index]);
2003 			LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2004 			    (void *)fini_addr[index], 0, 0, elm->obj->path);
2005 			call_initfini_pointer(elm->obj, fini_addr[index]);
2006 		    }
2007 	        }
2008 	    }
2009 	    if (elm->obj->fini != (Elf_Addr)NULL) {
2010 		dbg("DSO: calling fini function for %s at %p", elm->obj->path,
2011 		    (void *)elm->obj->fini);
2012 		LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2013 		    0, 0, elm->obj->path);
2014 	        call_initfini_pointer(elm->obj, elm->obj->fini);
2015 	    }
2016 	    wlock_acquire(rtld_bind_lock, lockstate);
2017 	    /* No need to free anything if process is going down. */
2018 	    if (root != NULL)
2019 		free(elm);
2020 	    /*
2021 	     * We must restart the list traversal after every fini call
2022 	     * because a dlclose() call from the fini function or from
2023 	     * another thread might have modified the reference counts.
2024 	     */
2025 	    break;
2026 	}
2027     } while (elm != NULL);
2028     errmsg_restore(saved_msg);
2029 }
2030 
2031 /*
2032  * If the main program is defined with a .preinit_array section, call
2033  * each function in order.  This must occur before the initialization
2034  * of any shared object or the main program.
2035  */
2036 static void
2037 preinitialize_main_object (void)
2038 {
2039     Elf_Addr *init_addr;
2040     int index;
2041 
2042     init_addr = (Elf_Addr *)obj_main->preinit_array;
2043     if (init_addr == (Elf_Addr)NULL)
2044 	return;
2045 
2046     for (index = 0; index < obj_main->preinit_array_num; index++)
2047 	if (init_addr[index] != 0 && init_addr[index] != 1) {
2048 	    dbg("Calling preinit array function for %s at %p",
2049 		(void *) obj_main->path, (void *)init_addr[index]);
2050 	    LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)init_addr[index],
2051 		0, 0, obj_main->path);
2052 	    call_array_pointer(init_addr[index], glac, glav, environ);
2053 	}
2054 }
2055 
2056 /*
2057  * Call the initialization functions for each of the objects in
2058  * "list".  All of the objects are expected to have non-NULL init
2059  * functions.
2060  */
2061 static void
2062 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2063 {
2064     Objlist_Entry *elm;
2065     Obj_Entry *obj;
2066     char *saved_msg;
2067     Elf_Addr *init_addr;
2068     int index;
2069 
2070     /*
2071      * Clean init_scanned flag so that objects can be rechecked and
2072      * possibly initialized earlier if any of vectors called below
2073      * cause the change by using dlopen.
2074      */
2075     for (obj = obj_list;  obj != NULL;  obj = obj->next)
2076 	obj->init_scanned = false;
2077 
2078     /*
2079      * Preserve the current error message since an init function might
2080      * call into the dynamic linker and overwrite it.
2081      */
2082     saved_msg = errmsg_save();
2083     STAILQ_FOREACH(elm, list, link) {
2084 	if (elm->obj->init_done) /* Initialized early. */
2085 	    continue;
2086 
2087 	/*
2088 	 * Race: other thread might try to use this object before current
2089 	 * one completes the initilization. Not much can be done here
2090 	 * without better locking.
2091 	 */
2092 	elm->obj->init_done = true;
2093 	lock_release(rtld_bind_lock, lockstate);
2094 
2095         /*
2096          * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.  When
2097          * this happens, DT_INIT is processed first.  It is possible to
2098          * encounter DT_INIT_ARRAY elements with values of 0 or 1, but they
2099          * need to be ignored.
2100          */
2101          if (elm->obj->init != (Elf_Addr)NULL) {
2102 	    dbg("DSO: calling init function for %s at %p", elm->obj->path,
2103 	        (void *)elm->obj->init);
2104 	    LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2105 	        0, 0, elm->obj->path);
2106 	    call_initfini_pointer(elm->obj, elm->obj->init);
2107 	}
2108 	init_addr = (Elf_Addr *)elm->obj->init_array;
2109 	if (init_addr != (Elf_Addr)NULL) {
2110 	    for (index = 0; index < elm->obj->init_array_num; index++)
2111 		if (init_addr[index] != 0 && init_addr[index] != 1) {
2112 		    dbg("DSO Array: calling init function for %s at %p",
2113 			elm->obj->path, (void *)init_addr[index]);
2114 		    LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2115 			(void *)init_addr[index], 0, 0, elm->obj->path);
2116 		    call_array_pointer(init_addr[index], glac, glav, environ);
2117 		}
2118 	}
2119 	wlock_acquire(rtld_bind_lock, lockstate);
2120     }
2121     errmsg_restore(saved_msg);
2122 }
2123 
2124 static void
2125 objlist_clear(Objlist *list)
2126 {
2127     Objlist_Entry *elm;
2128 
2129     while (!STAILQ_EMPTY(list)) {
2130 	elm = STAILQ_FIRST(list);
2131 	STAILQ_REMOVE_HEAD(list, link);
2132 	free(elm);
2133     }
2134 }
2135 
2136 static Objlist_Entry *
2137 objlist_find(Objlist *list, const Obj_Entry *obj)
2138 {
2139     Objlist_Entry *elm;
2140 
2141     STAILQ_FOREACH(elm, list, link)
2142 	if (elm->obj == obj)
2143 	    return elm;
2144     return NULL;
2145 }
2146 
2147 static void
2148 objlist_init(Objlist *list)
2149 {
2150     STAILQ_INIT(list);
2151 }
2152 
2153 static void
2154 objlist_push_head(Objlist *list, Obj_Entry *obj)
2155 {
2156     Objlist_Entry *elm;
2157 
2158     elm = NEW(Objlist_Entry);
2159     elm->obj = obj;
2160     STAILQ_INSERT_HEAD(list, elm, link);
2161 }
2162 
2163 static void
2164 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2165 {
2166     Objlist_Entry *elm;
2167 
2168     elm = NEW(Objlist_Entry);
2169     elm->obj = obj;
2170     STAILQ_INSERT_TAIL(list, elm, link);
2171 }
2172 
2173 static void
2174 objlist_remove(Objlist *list, Obj_Entry *obj)
2175 {
2176     Objlist_Entry *elm;
2177 
2178     if ((elm = objlist_find(list, obj)) != NULL) {
2179 	STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2180 	free(elm);
2181     }
2182 }
2183 
2184 /*
2185  * Relocate newly-loaded shared objects.  The argument is a pointer to
2186  * the Obj_Entry for the first such object.  All objects from the first
2187  * to the end of the list of objects are relocated.  Returns 0 on success,
2188  * or -1 on failure.
2189  */
2190 static int
2191 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2192     RtldLockState *lockstate)
2193 {
2194     Obj_Entry *obj;
2195 
2196     for (obj = first;  obj != NULL;  obj = obj->next) {
2197 	if (obj != rtldobj)
2198 	    dbg("relocating \"%s\"", obj->path);
2199 	if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
2200 	    obj->symtab == NULL || obj->strtab == NULL) {
2201 	    _rtld_error("%s: Shared object has no run-time symbol table",
2202 	      obj->path);
2203 	    return -1;
2204 	}
2205 
2206 	if (obj->textrel) {
2207 	    /* There are relocations to the write-protected text segment. */
2208 	    if (mprotect(obj->mapbase, obj->textsize,
2209 	      PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2210 		_rtld_error("%s: Cannot write-enable text segment: %s",
2211 		  obj->path, strerror(errno));
2212 		return -1;
2213 	    }
2214 	}
2215 
2216 	/* Process the non-PLT relocations. */
2217 	if (reloc_non_plt(obj, rtldobj, lockstate))
2218 		return -1;
2219 
2220 	/*
2221 	 * Reprotect the text segment.  Make sure it is included in the
2222 	 * core dump since we modified it.  This unfortunately causes the
2223 	 * entire text segment to core-out but we don't have much of a
2224 	 * choice.  We could try to only reenable core dumps on pages
2225 	 * in which relocations occured but that is likely most of the text
2226 	 * pages anyway, and even that would not work because the rest of
2227 	 * the text pages would wind up as a read-only OBJT_DEFAULT object
2228 	 * (created due to our modifications) backed by the original OBJT_VNODE
2229 	 * object, and the ELF coredump code is currently only able to dump
2230 	 * vnode records for pure vnode-backed mappings, not vnode backings
2231 	 * to memory objects.
2232 	 */
2233 	if (obj->textrel) {
2234 	    madvise(obj->mapbase, obj->textsize, MADV_CORE);
2235 	    if (mprotect(obj->mapbase, obj->textsize,
2236 	      PROT_READ|PROT_EXEC) == -1) {
2237 		_rtld_error("%s: Cannot write-protect text segment: %s",
2238 		  obj->path, strerror(errno));
2239 		return -1;
2240 	    }
2241 	}
2242 
2243 
2244 	/* Set the special PLT or GOT entries. */
2245 	init_pltgot(obj);
2246 
2247 	/* Process the PLT relocations. */
2248 	if (reloc_plt(obj) == -1)
2249 	    return -1;
2250 	/* Relocate the jump slots if we are doing immediate binding. */
2251 	if (obj->bind_now || bind_now)
2252 	    if (reloc_jmpslots(obj, lockstate) == -1)
2253 		return -1;
2254 
2255 	/*
2256 	 * Set up the magic number and version in the Obj_Entry.  These
2257 	 * were checked in the crt1.o from the original ElfKit, so we
2258 	 * set them for backward compatibility.
2259 	 */
2260 	obj->magic = RTLD_MAGIC;
2261 	obj->version = RTLD_VERSION;
2262 
2263 	/*
2264 	 * Set relocated data to read-only status if protection specified
2265 	 */
2266 
2267 	if (obj->relro_size) {
2268 	    if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2269 		_rtld_error("%s: Cannot enforce relro relocation: %s",
2270 		  obj->path, strerror(errno));
2271 		return -1;
2272 	    }
2273 	}
2274     }
2275 
2276     return (0);
2277 }
2278 
2279 /*
2280  * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2281  * referencing STT_GNU_IFUNC symbols is postponed till the other
2282  * relocations are done.  The indirect functions specified as
2283  * ifunc are allowed to call other symbols, so we need to have
2284  * objects relocated before asking for resolution from indirects.
2285  *
2286  * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2287  * instead of the usual lazy handling of PLT slots.  It is
2288  * consistent with how GNU does it.
2289  */
2290 static int
2291 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2292 {
2293 	if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2294 		return (-1);
2295 	if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2296 	    reloc_gnu_ifunc(obj, lockstate) == -1)
2297 		return (-1);
2298 	return (0);
2299 }
2300 
2301 static int
2302 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2303 {
2304 	Obj_Entry *obj;
2305 
2306 	for (obj = first;  obj != NULL;  obj = obj->next) {
2307 		if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2308 			return (-1);
2309 	}
2310 	return (0);
2311 }
2312 
2313 static int
2314 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2315 {
2316 	Objlist_Entry *elm;
2317 
2318 	STAILQ_FOREACH(elm, list, link) {
2319 		if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2320 			return (-1);
2321 	}
2322 	return (0);
2323 }
2324 
2325 /*
2326  * Cleanup procedure.  It will be called (by the atexit mechanism) just
2327  * before the process exits.
2328  */
2329 static void
2330 rtld_exit(void)
2331 {
2332     RtldLockState lockstate;
2333 
2334     wlock_acquire(rtld_bind_lock, &lockstate);
2335     dbg("rtld_exit()");
2336     objlist_call_fini(&list_fini, NULL, &lockstate);
2337     /* No need to remove the items from the list, since we are exiting. */
2338     if (!libmap_disable)
2339         lm_fini();
2340     lock_release(rtld_bind_lock, &lockstate);
2341 }
2342 
2343 static void *
2344 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2345 {
2346     if (path == NULL)
2347 	return (NULL);
2348 
2349     path += strspn(path, ":;");
2350     while (*path != '\0') {
2351 	size_t len;
2352 	char  *res;
2353 
2354 	len = strcspn(path, ":;");
2355 	res = callback(path, len, arg);
2356 
2357 	if (res != NULL)
2358 	    return (res);
2359 
2360 	path += len;
2361 	path += strspn(path, ":;");
2362     }
2363 
2364     return (NULL);
2365 }
2366 
2367 struct try_library_args {
2368     const char	*name;
2369     size_t	 namelen;
2370     char	*buffer;
2371     size_t	 buflen;
2372 };
2373 
2374 static void *
2375 try_library_path(const char *dir, size_t dirlen, void *param)
2376 {
2377     struct try_library_args *arg;
2378 
2379     arg = param;
2380     if (*dir == '/' || trust) {
2381 	char *pathname;
2382 
2383 	if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2384 		return (NULL);
2385 
2386 	pathname = arg->buffer;
2387 	strncpy(pathname, dir, dirlen);
2388 	pathname[dirlen] = '/';
2389 	strcpy(pathname + dirlen + 1, arg->name);
2390 
2391 	dbg("  Trying \"%s\"", pathname);
2392 	if (access(pathname, F_OK) == 0) {		/* We found it */
2393 	    pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2394 	    strcpy(pathname, arg->buffer);
2395 	    return (pathname);
2396 	}
2397     }
2398     return (NULL);
2399 }
2400 
2401 static char *
2402 search_library_path(const char *name, const char *path)
2403 {
2404     char *p;
2405     struct try_library_args arg;
2406 
2407     if (path == NULL)
2408 	return NULL;
2409 
2410     arg.name = name;
2411     arg.namelen = strlen(name);
2412     arg.buffer = xmalloc(PATH_MAX);
2413     arg.buflen = PATH_MAX;
2414 
2415     p = path_enumerate(path, try_library_path, &arg);
2416 
2417     free(arg.buffer);
2418 
2419     return (p);
2420 }
2421 
2422 int
2423 dlclose(void *handle)
2424 {
2425     Obj_Entry *root;
2426     RtldLockState lockstate;
2427 
2428     wlock_acquire(rtld_bind_lock, &lockstate);
2429     root = dlcheck(handle);
2430     if (root == NULL) {
2431 	lock_release(rtld_bind_lock, &lockstate);
2432 	return -1;
2433     }
2434     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2435 	root->path);
2436 
2437     /* Unreference the object and its dependencies. */
2438     root->dl_refcount--;
2439 
2440     if (root->refcount == 1) {
2441 	/*
2442 	 * The object will be no longer referenced, so we must unload it.
2443 	 * First, call the fini functions.
2444 	 */
2445 	objlist_call_fini(&list_fini, root, &lockstate);
2446 
2447 	unref_dag(root);
2448 
2449 	/* Finish cleaning up the newly-unreferenced objects. */
2450 	GDB_STATE(RT_DELETE,&root->linkmap);
2451 	unload_object(root);
2452 	GDB_STATE(RT_CONSISTENT,NULL);
2453     } else
2454 	unref_dag(root);
2455 
2456     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2457     lock_release(rtld_bind_lock, &lockstate);
2458     return 0;
2459 }
2460 
2461 char *
2462 dlerror(void)
2463 {
2464     char *msg = error_message;
2465     error_message = NULL;
2466     return msg;
2467 }
2468 
2469 void *
2470 dlopen(const char *name, int mode)
2471 {
2472     RtldLockState lockstate;
2473     int lo_flags;
2474 
2475     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2476     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2477     if (ld_tracing != NULL) {
2478 	rlock_acquire(rtld_bind_lock, &lockstate);
2479 	if (sigsetjmp(lockstate.env, 0) != 0)
2480 	    lock_upgrade(rtld_bind_lock, &lockstate);
2481 	environ = (char **)*get_program_var_addr("environ", &lockstate);
2482 	lock_release(rtld_bind_lock, &lockstate);
2483     }
2484     lo_flags = RTLD_LO_DLOPEN;
2485     if (mode & RTLD_NODELETE)
2486 	    lo_flags |= RTLD_LO_NODELETE;
2487     if (mode & RTLD_NOLOAD)
2488 	    lo_flags |= RTLD_LO_NOLOAD;
2489     if (ld_tracing != NULL)
2490 	    lo_flags |= RTLD_LO_TRACE;
2491 
2492     return (dlopen_object(name, obj_main, lo_flags,
2493       mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2494 }
2495 
2496 static void
2497 dlopen_cleanup(Obj_Entry *obj)
2498 {
2499 
2500 	obj->dl_refcount--;
2501 	unref_dag(obj);
2502 	if (obj->refcount == 0)
2503 		unload_object(obj);
2504 }
2505 
2506 static Obj_Entry *
2507 dlopen_object(const char *name, Obj_Entry *refobj, int lo_flags, int mode)
2508 {
2509     Obj_Entry **old_obj_tail;
2510     Obj_Entry *obj;
2511     Objlist initlist;
2512     RtldLockState lockstate;
2513     int result;
2514 
2515     objlist_init(&initlist);
2516 
2517     wlock_acquire(rtld_bind_lock, &lockstate);
2518     GDB_STATE(RT_ADD,NULL);
2519 
2520     old_obj_tail = obj_tail;
2521     obj = NULL;
2522     if (name == NULL) {
2523 	obj = obj_main;
2524 	obj->refcount++;
2525     } else {
2526 	obj = load_object(name, refobj, lo_flags);
2527     }
2528 
2529     if (obj) {
2530 	obj->dl_refcount++;
2531 	if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2532 	    objlist_push_tail(&list_global, obj);
2533 	if (*old_obj_tail != NULL) {		/* We loaded something new. */
2534 	    assert(*old_obj_tail == obj);
2535 	    result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2536 	    init_dag(obj);
2537 	    ref_dag(obj);
2538 	    if (result != -1)
2539 		result = rtld_verify_versions(&obj->dagmembers);
2540 	    if (result != -1 && ld_tracing)
2541 		goto trace;
2542 	    if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2543 	      == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2544 		dlopen_cleanup(obj);
2545 		obj = NULL;
2546 	    } else {
2547 		/* Make list of init functions to call. */
2548 		initlist_add_objects(obj, &obj->next, &initlist);
2549 	    }
2550 	} else {
2551 
2552 	    /*
2553 	     * Bump the reference counts for objects on this DAG.  If
2554 	     * this is the first dlopen() call for the object that was
2555 	     * already loaded as a dependency, initialize the dag
2556 	     * starting at it.
2557 	     */
2558 	    init_dag(obj);
2559 	    ref_dag(obj);
2560 
2561 	    if ((lo_flags & RTLD_LO_TRACE) != 0)
2562 		goto trace;
2563 	}
2564 	if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2565 	  obj->z_nodelete) && !obj->ref_nodel) {
2566 	    dbg("obj %s nodelete", obj->path);
2567 	    ref_dag(obj);
2568 	    obj->z_nodelete = obj->ref_nodel = true;
2569 	}
2570     }
2571 
2572     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2573 	name);
2574     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2575 
2576     map_stacks_exec(&lockstate);
2577 
2578     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2579       &lockstate) == -1) {
2580 	objlist_clear(&initlist);
2581 	dlopen_cleanup(obj);
2582 	lock_release(rtld_bind_lock, &lockstate);
2583 	return (NULL);
2584     }
2585 
2586     /* Call the init functions. */
2587     objlist_call_init(&initlist, &lockstate);
2588     objlist_clear(&initlist);
2589     lock_release(rtld_bind_lock, &lockstate);
2590     return obj;
2591 trace:
2592     trace_loaded_objects(obj);
2593     lock_release(rtld_bind_lock, &lockstate);
2594     exit(0);
2595 }
2596 
2597 static void *
2598 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2599     int flags)
2600 {
2601     DoneList donelist;
2602     const Obj_Entry *obj, *defobj;
2603     const Elf_Sym *def;
2604     SymLook req;
2605     RtldLockState lockstate;
2606     int res;
2607 
2608     def = NULL;
2609     defobj = NULL;
2610     symlook_init(&req, name);
2611     req.ventry = ve;
2612     req.flags = flags | SYMLOOK_IN_PLT;
2613     req.lockstate = &lockstate;
2614 
2615     rlock_acquire(rtld_bind_lock, &lockstate);
2616     if (sigsetjmp(lockstate.env, 0) != 0)
2617 	    lock_upgrade(rtld_bind_lock, &lockstate);
2618     if (handle == NULL || handle == RTLD_NEXT ||
2619 	handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2620 
2621 	if ((obj = obj_from_addr(retaddr)) == NULL) {
2622 	    _rtld_error("Cannot determine caller's shared object");
2623 	    lock_release(rtld_bind_lock, &lockstate);
2624 	    return NULL;
2625 	}
2626 	if (handle == NULL) {	/* Just the caller's shared object. */
2627 	    res = symlook_obj(&req, obj);
2628 	    if (res == 0) {
2629 		def = req.sym_out;
2630 		defobj = req.defobj_out;
2631 	    }
2632 	} else if (handle == RTLD_NEXT || /* Objects after caller's */
2633 		   handle == RTLD_SELF) { /* ... caller included */
2634 	    if (handle == RTLD_NEXT)
2635 		obj = obj->next;
2636 	    for (; obj != NULL; obj = obj->next) {
2637 		res = symlook_obj(&req, obj);
2638 		if (res == 0) {
2639 		    if (def == NULL ||
2640 		      ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2641 			def = req.sym_out;
2642 			defobj = req.defobj_out;
2643 			if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2644 			    break;
2645 		    }
2646 		}
2647 	    }
2648 	    /*
2649 	     * Search the dynamic linker itself, and possibly resolve the
2650 	     * symbol from there.  This is how the application links to
2651 	     * dynamic linker services such as dlopen.
2652 	     */
2653 	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2654 		res = symlook_obj(&req, &obj_rtld);
2655 		if (res == 0 && is_exported(req.sym_out)) {
2656 		    def = req.sym_out;
2657 		    defobj = req.defobj_out;
2658 		}
2659 	    }
2660 	} else {
2661 	    assert(handle == RTLD_DEFAULT);
2662 	    res = symlook_default(&req, obj);
2663 	    if (res == 0) {
2664 		defobj = req.defobj_out;
2665 		def = req.sym_out;
2666 	    }
2667 	}
2668     } else {
2669 	if ((obj = dlcheck(handle)) == NULL) {
2670 	    lock_release(rtld_bind_lock, &lockstate);
2671 	    return NULL;
2672 	}
2673 
2674 	donelist_init(&donelist);
2675 	if (obj->mainprog) {
2676             /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2677 	    res = symlook_global(&req, &donelist);
2678 	    if (res == 0) {
2679 		def = req.sym_out;
2680 		defobj = req.defobj_out;
2681 	    }
2682 	    /*
2683 	     * Search the dynamic linker itself, and possibly resolve the
2684 	     * symbol from there.  This is how the application links to
2685 	     * dynamic linker services such as dlopen.
2686 	     */
2687 	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2688 		res = symlook_obj(&req, &obj_rtld);
2689 		if (res == 0) {
2690 		    def = req.sym_out;
2691 		    defobj = req.defobj_out;
2692 		}
2693 	    }
2694 	}
2695 	else {
2696 	    /* Search the whole DAG rooted at the given object. */
2697 	    res = symlook_list(&req, &obj->dagmembers, &donelist);
2698 	    if (res == 0) {
2699 		def = req.sym_out;
2700 		defobj = req.defobj_out;
2701 	    }
2702 	}
2703     }
2704 
2705     if (def != NULL) {
2706 	lock_release(rtld_bind_lock, &lockstate);
2707 
2708 	/*
2709 	 * The value required by the caller is derived from the value
2710 	 * of the symbol. For the ia64 architecture, we need to
2711 	 * construct a function descriptor which the caller can use to
2712 	 * call the function with the right 'gp' value. For other
2713 	 * architectures and for non-functions, the value is simply
2714 	 * the relocated value of the symbol.
2715 	 */
2716 	if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2717 	    return (make_function_pointer(def, defobj));
2718 	else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2719 	    return (rtld_resolve_ifunc(defobj, def));
2720 	else
2721 	    return (defobj->relocbase + def->st_value);
2722     }
2723 
2724     _rtld_error("Undefined symbol \"%s\"", name);
2725     lock_release(rtld_bind_lock, &lockstate);
2726     return NULL;
2727 }
2728 
2729 void *
2730 dlsym(void *handle, const char *name)
2731 {
2732 	return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2733 	    SYMLOOK_DLSYM);
2734 }
2735 
2736 dlfunc_t
2737 dlfunc(void *handle, const char *name)
2738 {
2739 	union {
2740 		void *d;
2741 		dlfunc_t f;
2742 	} rv;
2743 
2744 	rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2745 	    SYMLOOK_DLSYM);
2746 	return (rv.f);
2747 }
2748 
2749 void *
2750 dlvsym(void *handle, const char *name, const char *version)
2751 {
2752 	Ver_Entry ventry;
2753 
2754 	ventry.name = version;
2755 	ventry.file = NULL;
2756 	ventry.hash = elf_hash(version);
2757 	ventry.flags= 0;
2758 	return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2759 	    SYMLOOK_DLSYM);
2760 }
2761 
2762 int
2763 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2764 {
2765     const Obj_Entry *obj;
2766     RtldLockState lockstate;
2767 
2768     rlock_acquire(rtld_bind_lock, &lockstate);
2769     obj = obj_from_addr(addr);
2770     if (obj == NULL) {
2771         _rtld_error("No shared object contains address");
2772 	lock_release(rtld_bind_lock, &lockstate);
2773         return (0);
2774     }
2775     rtld_fill_dl_phdr_info(obj, phdr_info);
2776     lock_release(rtld_bind_lock, &lockstate);
2777     return (1);
2778 }
2779 
2780 int
2781 dladdr(const void *addr, Dl_info *info)
2782 {
2783     const Obj_Entry *obj;
2784     const Elf_Sym *def;
2785     void *symbol_addr;
2786     unsigned long symoffset;
2787     RtldLockState lockstate;
2788 
2789     rlock_acquire(rtld_bind_lock, &lockstate);
2790     obj = obj_from_addr(addr);
2791     if (obj == NULL) {
2792         _rtld_error("No shared object contains address");
2793 	lock_release(rtld_bind_lock, &lockstate);
2794         return 0;
2795     }
2796     info->dli_fname = obj->path;
2797     info->dli_fbase = obj->mapbase;
2798     info->dli_saddr = NULL;
2799     info->dli_sname = NULL;
2800 
2801     /*
2802      * Walk the symbol list looking for the symbol whose address is
2803      * closest to the address sent in.
2804      */
2805     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2806         def = obj->symtab + symoffset;
2807 
2808         /*
2809          * For skip the symbol if st_shndx is either SHN_UNDEF or
2810          * SHN_COMMON.
2811          */
2812         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2813             continue;
2814 
2815         /*
2816          * If the symbol is greater than the specified address, or if it
2817          * is further away from addr than the current nearest symbol,
2818          * then reject it.
2819          */
2820         symbol_addr = obj->relocbase + def->st_value;
2821         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2822             continue;
2823 
2824         /* Update our idea of the nearest symbol. */
2825         info->dli_sname = obj->strtab + def->st_name;
2826         info->dli_saddr = symbol_addr;
2827 
2828         /* Exact match? */
2829         if (info->dli_saddr == addr)
2830             break;
2831     }
2832     lock_release(rtld_bind_lock, &lockstate);
2833     return 1;
2834 }
2835 
2836 int
2837 dlinfo(void *handle, int request, void *p)
2838 {
2839     const Obj_Entry *obj;
2840     RtldLockState lockstate;
2841     int error;
2842 
2843     rlock_acquire(rtld_bind_lock, &lockstate);
2844 
2845     if (handle == NULL || handle == RTLD_SELF) {
2846 	void *retaddr;
2847 
2848 	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
2849 	if ((obj = obj_from_addr(retaddr)) == NULL)
2850 	    _rtld_error("Cannot determine caller's shared object");
2851     } else
2852 	obj = dlcheck(handle);
2853 
2854     if (obj == NULL) {
2855 	lock_release(rtld_bind_lock, &lockstate);
2856 	return (-1);
2857     }
2858 
2859     error = 0;
2860     switch (request) {
2861     case RTLD_DI_LINKMAP:
2862 	*((struct link_map const **)p) = &obj->linkmap;
2863 	break;
2864     case RTLD_DI_ORIGIN:
2865 	error = rtld_dirname(obj->path, p);
2866 	break;
2867 
2868     case RTLD_DI_SERINFOSIZE:
2869     case RTLD_DI_SERINFO:
2870 	error = do_search_info(obj, request, (struct dl_serinfo *)p);
2871 	break;
2872 
2873     default:
2874 	_rtld_error("Invalid request %d passed to dlinfo()", request);
2875 	error = -1;
2876     }
2877 
2878     lock_release(rtld_bind_lock, &lockstate);
2879 
2880     return (error);
2881 }
2882 
2883 static void
2884 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2885 {
2886 
2887 	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2888 	phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2889 	    STAILQ_FIRST(&obj->names)->name : obj->path;
2890 	phdr_info->dlpi_phdr = obj->phdr;
2891 	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2892 	phdr_info->dlpi_tls_modid = obj->tlsindex;
2893 	phdr_info->dlpi_tls_data = obj->tlsinit;
2894 	phdr_info->dlpi_adds = obj_loads;
2895 	phdr_info->dlpi_subs = obj_loads - obj_count;
2896 }
2897 
2898 int
2899 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2900 {
2901     struct dl_phdr_info phdr_info;
2902     const Obj_Entry *obj;
2903     RtldLockState bind_lockstate, phdr_lockstate;
2904     int error;
2905 
2906     wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2907     rlock_acquire(rtld_bind_lock, &bind_lockstate);
2908 
2909     error = 0;
2910 
2911     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2912 	rtld_fill_dl_phdr_info(obj, &phdr_info);
2913 	if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2914 		break;
2915 
2916     }
2917     lock_release(rtld_bind_lock, &bind_lockstate);
2918     lock_release(rtld_phdr_lock, &phdr_lockstate);
2919 
2920     return (error);
2921 }
2922 
2923 struct fill_search_info_args {
2924     int		 request;
2925     unsigned int flags;
2926     Dl_serinfo  *serinfo;
2927     Dl_serpath  *serpath;
2928     char	*strspace;
2929 };
2930 
2931 static void *
2932 fill_search_info(const char *dir, size_t dirlen, void *param)
2933 {
2934     struct fill_search_info_args *arg;
2935 
2936     arg = param;
2937 
2938     if (arg->request == RTLD_DI_SERINFOSIZE) {
2939 	arg->serinfo->dls_cnt ++;
2940 	arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2941     } else {
2942 	struct dl_serpath *s_entry;
2943 
2944 	s_entry = arg->serpath;
2945 	s_entry->dls_name  = arg->strspace;
2946 	s_entry->dls_flags = arg->flags;
2947 
2948 	strncpy(arg->strspace, dir, dirlen);
2949 	arg->strspace[dirlen] = '\0';
2950 
2951 	arg->strspace += dirlen + 1;
2952 	arg->serpath++;
2953     }
2954 
2955     return (NULL);
2956 }
2957 
2958 static int
2959 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2960 {
2961     struct dl_serinfo _info;
2962     struct fill_search_info_args args;
2963 
2964     args.request = RTLD_DI_SERINFOSIZE;
2965     args.serinfo = &_info;
2966 
2967     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2968     _info.dls_cnt  = 0;
2969 
2970     path_enumerate(ld_library_path, fill_search_info, &args);
2971     path_enumerate(obj->rpath, fill_search_info, &args);
2972     path_enumerate(gethints(), fill_search_info, &args);
2973     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2974 
2975 
2976     if (request == RTLD_DI_SERINFOSIZE) {
2977 	info->dls_size = _info.dls_size;
2978 	info->dls_cnt = _info.dls_cnt;
2979 	return (0);
2980     }
2981 
2982     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2983 	_rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2984 	return (-1);
2985     }
2986 
2987     args.request  = RTLD_DI_SERINFO;
2988     args.serinfo  = info;
2989     args.serpath  = &info->dls_serpath[0];
2990     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2991 
2992     args.flags = LA_SER_LIBPATH;
2993     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2994 	return (-1);
2995 
2996     args.flags = LA_SER_RUNPATH;
2997     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2998 	return (-1);
2999 
3000     args.flags = LA_SER_CONFIG;
3001     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
3002 	return (-1);
3003 
3004     args.flags = LA_SER_DEFAULT;
3005     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3006 	return (-1);
3007     return (0);
3008 }
3009 
3010 static int
3011 rtld_dirname(const char *path, char *bname)
3012 {
3013     const char *endp;
3014 
3015     /* Empty or NULL string gets treated as "." */
3016     if (path == NULL || *path == '\0') {
3017 	bname[0] = '.';
3018 	bname[1] = '\0';
3019 	return (0);
3020     }
3021 
3022     /* Strip trailing slashes */
3023     endp = path + strlen(path) - 1;
3024     while (endp > path && *endp == '/')
3025 	endp--;
3026 
3027     /* Find the start of the dir */
3028     while (endp > path && *endp != '/')
3029 	endp--;
3030 
3031     /* Either the dir is "/" or there are no slashes */
3032     if (endp == path) {
3033 	bname[0] = *endp == '/' ? '/' : '.';
3034 	bname[1] = '\0';
3035 	return (0);
3036     } else {
3037 	do {
3038 	    endp--;
3039 	} while (endp > path && *endp == '/');
3040     }
3041 
3042     if (endp - path + 2 > PATH_MAX)
3043     {
3044 	_rtld_error("Filename is too long: %s", path);
3045 	return(-1);
3046     }
3047 
3048     strncpy(bname, path, endp - path + 1);
3049     bname[endp - path + 1] = '\0';
3050     return (0);
3051 }
3052 
3053 static int
3054 rtld_dirname_abs(const char *path, char *base)
3055 {
3056 	char base_rel[PATH_MAX];
3057 
3058 	if (rtld_dirname(path, base) == -1)
3059 		return (-1);
3060 	if (base[0] == '/')
3061 		return (0);
3062 	if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3063 	    strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3064 	    strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3065 		return (-1);
3066 	strcpy(base, base_rel);
3067 	return (0);
3068 }
3069 
3070 static void
3071 linkmap_add(Obj_Entry *obj)
3072 {
3073     struct link_map *l = &obj->linkmap;
3074     struct link_map *prev;
3075 
3076     obj->linkmap.l_name = obj->path;
3077     obj->linkmap.l_addr = obj->mapbase;
3078     obj->linkmap.l_ld = obj->dynamic;
3079 #ifdef __mips__
3080     /* GDB needs load offset on MIPS to use the symbols */
3081     obj->linkmap.l_offs = obj->relocbase;
3082 #endif
3083 
3084     if (r_debug.r_map == NULL) {
3085 	r_debug.r_map = l;
3086 	return;
3087     }
3088 
3089     /*
3090      * Scan to the end of the list, but not past the entry for the
3091      * dynamic linker, which we want to keep at the very end.
3092      */
3093     for (prev = r_debug.r_map;
3094       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3095       prev = prev->l_next)
3096 	;
3097 
3098     /* Link in the new entry. */
3099     l->l_prev = prev;
3100     l->l_next = prev->l_next;
3101     if (l->l_next != NULL)
3102 	l->l_next->l_prev = l;
3103     prev->l_next = l;
3104 }
3105 
3106 static void
3107 linkmap_delete(Obj_Entry *obj)
3108 {
3109     struct link_map *l = &obj->linkmap;
3110 
3111     if (l->l_prev == NULL) {
3112 	if ((r_debug.r_map = l->l_next) != NULL)
3113 	    l->l_next->l_prev = NULL;
3114 	return;
3115     }
3116 
3117     if ((l->l_prev->l_next = l->l_next) != NULL)
3118 	l->l_next->l_prev = l->l_prev;
3119 }
3120 
3121 /*
3122  * Function for the debugger to set a breakpoint on to gain control.
3123  *
3124  * The two parameters allow the debugger to easily find and determine
3125  * what the runtime loader is doing and to whom it is doing it.
3126  *
3127  * When the loadhook trap is hit (r_debug_state, set at program
3128  * initialization), the arguments can be found on the stack:
3129  *
3130  *  +8   struct link_map *m
3131  *  +4   struct r_debug  *rd
3132  *  +0   RetAddr
3133  */
3134 void
3135 r_debug_state(struct r_debug* rd, struct link_map *m)
3136 {
3137     /*
3138      * The following is a hack to force the compiler to emit calls to
3139      * this function, even when optimizing.  If the function is empty,
3140      * the compiler is not obliged to emit any code for calls to it,
3141      * even when marked __noinline.  However, gdb depends on those
3142      * calls being made.
3143      */
3144     __asm __volatile("" : : : "memory");
3145 }
3146 
3147 /*
3148  * Get address of the pointer variable in the main program.
3149  * Prefer non-weak symbol over the weak one.
3150  */
3151 static const void **
3152 get_program_var_addr(const char *name, RtldLockState *lockstate)
3153 {
3154     SymLook req;
3155     DoneList donelist;
3156 
3157     symlook_init(&req, name);
3158     req.lockstate = lockstate;
3159     donelist_init(&donelist);
3160     if (symlook_global(&req, &donelist) != 0)
3161 	return (NULL);
3162     if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3163 	return ((const void **)make_function_pointer(req.sym_out,
3164 	  req.defobj_out));
3165     else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3166 	return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3167     else
3168 	    return ((const void **)(req.defobj_out->relocbase +
3169 	      req.sym_out->st_value));
3170 }
3171 
3172 /*
3173  * Set a pointer variable in the main program to the given value.  This
3174  * is used to set key variables such as "environ" before any of the
3175  * init functions are called.
3176  */
3177 static void
3178 set_program_var(const char *name, const void *value)
3179 {
3180     const void **addr;
3181 
3182     if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3183 	dbg("\"%s\": *%p <-- %p", name, addr, value);
3184 	*addr = value;
3185     }
3186 }
3187 
3188 /*
3189  * Search the global objects, including dependencies and main object,
3190  * for the given symbol.
3191  */
3192 static int
3193 symlook_global(SymLook *req, DoneList *donelist)
3194 {
3195     SymLook req1;
3196     const Objlist_Entry *elm;
3197     int res;
3198 
3199     symlook_init_from_req(&req1, req);
3200 
3201     /* Search all objects loaded at program start up. */
3202     if (req->defobj_out == NULL ||
3203       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3204 	res = symlook_list(&req1, &list_main, donelist);
3205 	if (res == 0 && (req->defobj_out == NULL ||
3206 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3207 	    req->sym_out = req1.sym_out;
3208 	    req->defobj_out = req1.defobj_out;
3209 	    assert(req->defobj_out != NULL);
3210 	}
3211     }
3212 
3213     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3214     STAILQ_FOREACH(elm, &list_global, link) {
3215 	if (req->defobj_out != NULL &&
3216 	  ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3217 	    break;
3218 	res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3219 	if (res == 0 && (req->defobj_out == NULL ||
3220 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3221 	    req->sym_out = req1.sym_out;
3222 	    req->defobj_out = req1.defobj_out;
3223 	    assert(req->defobj_out != NULL);
3224 	}
3225     }
3226 
3227     return (req->sym_out != NULL ? 0 : ESRCH);
3228 }
3229 
3230 /*
3231  * This is a special version of getenv which is far more efficient
3232  * at finding LD_ environment vars.
3233  */
3234 static
3235 const char *
3236 _getenv_ld(const char *id)
3237 {
3238     const char *envp;
3239     int i, j;
3240     int idlen = strlen(id);
3241 
3242     if (ld_index == LD_ARY_CACHE)
3243 	return(getenv(id));
3244     if (ld_index == 0) {
3245 	for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
3246 	    if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
3247 		ld_ary[j++] = envp;
3248 	}
3249 	if (j == 0)
3250 		ld_ary[j++] = "";
3251 	ld_index = j;
3252     }
3253     for (i = ld_index - 1; i >= 0; --i) {
3254 	if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
3255 	    return(ld_ary[i] + idlen + 1);
3256     }
3257     return(NULL);
3258 }
3259 
3260 /*
3261  * Given a symbol name in a referencing object, find the corresponding
3262  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
3263  * no definition was found.  Returns a pointer to the Obj_Entry of the
3264  * defining object via the reference parameter DEFOBJ_OUT.
3265  */
3266 static int
3267 symlook_default(SymLook *req, const Obj_Entry *refobj)
3268 {
3269     DoneList donelist;
3270     const Objlist_Entry *elm;
3271     SymLook req1;
3272     int res;
3273 
3274     donelist_init(&donelist);
3275     symlook_init_from_req(&req1, req);
3276 
3277     /* Look first in the referencing object if linked symbolically. */
3278     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3279 	res = symlook_obj(&req1, refobj);
3280 	if (res == 0) {
3281 	    req->sym_out = req1.sym_out;
3282 	    req->defobj_out = req1.defobj_out;
3283 	    assert(req->defobj_out != NULL);
3284 	}
3285     }
3286 
3287     symlook_global(req, &donelist);
3288 
3289     /* Search all dlopened DAGs containing the referencing object. */
3290     STAILQ_FOREACH(elm, &refobj->dldags, link) {
3291 	if (req->sym_out != NULL &&
3292 	  ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3293 	    break;
3294 	res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3295 	if (res == 0 && (req->sym_out == NULL ||
3296 	  ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3297 	    req->sym_out = req1.sym_out;
3298 	    req->defobj_out = req1.defobj_out;
3299 	    assert(req->defobj_out != NULL);
3300 	}
3301     }
3302 
3303     /*
3304      * Search the dynamic linker itself, and possibly resolve the
3305      * symbol from there.  This is how the application links to
3306      * dynamic linker services such as dlopen.  Only the values listed
3307      * in the "exports" array can be resolved from the dynamic linker.
3308      */
3309     if (req->sym_out == NULL ||
3310       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3311 	res = symlook_obj(&req1, &obj_rtld);
3312 	if (res == 0 && is_exported(req1.sym_out)) {
3313 	    req->sym_out = req1.sym_out;
3314 	    req->defobj_out = req1.defobj_out;
3315 	    assert(req->defobj_out != NULL);
3316 	}
3317     }
3318 
3319     return (req->sym_out != NULL ? 0 : ESRCH);
3320 }
3321 
3322 static int
3323 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3324 {
3325     const Elf_Sym *def;
3326     const Obj_Entry *defobj;
3327     const Objlist_Entry *elm;
3328     SymLook req1;
3329     int res;
3330 
3331     def = NULL;
3332     defobj = NULL;
3333     STAILQ_FOREACH(elm, objlist, link) {
3334 	if (donelist_check(dlp, elm->obj))
3335 	    continue;
3336 	symlook_init_from_req(&req1, req);
3337 	if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3338 	    if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3339 		def = req1.sym_out;
3340 		defobj = req1.defobj_out;
3341 		if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3342 		    break;
3343 	    }
3344 	}
3345     }
3346     if (def != NULL) {
3347 	req->sym_out = def;
3348 	req->defobj_out = defobj;
3349 	return (0);
3350     }
3351     return (ESRCH);
3352 }
3353 
3354 /*
3355  * Search the chain of DAGS cointed to by the given Needed_Entry
3356  * for a symbol of the given name.  Each DAG is scanned completely
3357  * before advancing to the next one.  Returns a pointer to the symbol,
3358  * or NULL if no definition was found.
3359  */
3360 static int
3361 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3362 {
3363     const Elf_Sym *def;
3364     const Needed_Entry *n;
3365     const Obj_Entry *defobj;
3366     SymLook req1;
3367     int res;
3368 
3369     def = NULL;
3370     defobj = NULL;
3371     symlook_init_from_req(&req1, req);
3372     for (n = needed; n != NULL; n = n->next) {
3373 	if (n->obj == NULL ||
3374 	    (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3375 	    continue;
3376 	if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3377 	def = req1.sym_out;
3378 	defobj = req1.defobj_out;
3379 	    if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3380 		break;
3381 	}
3382     }
3383     if (def != NULL) {
3384 	req->sym_out = def;
3385 	req->defobj_out = defobj;
3386 	return (0);
3387     }
3388     return (ESRCH);
3389 }
3390 
3391 /*
3392  * Search the symbol table of a single shared object for a symbol of
3393  * the given name and version, if requested.  Returns a pointer to the
3394  * symbol, or NULL if no definition was found.  If the object is
3395  * filter, return filtered symbol from filtee.
3396  *
3397  * The symbol's hash value is passed in for efficiency reasons; that
3398  * eliminates many recomputations of the hash value.
3399  */
3400 int
3401 symlook_obj(SymLook *req, const Obj_Entry *obj)
3402 {
3403     DoneList donelist;
3404     SymLook req1;
3405     int res, mres;
3406 
3407     mres = symlook_obj1(req, obj);
3408     if (mres == 0) {
3409 	if (obj->needed_filtees != NULL) {
3410 	    load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3411 	    donelist_init(&donelist);
3412 	    symlook_init_from_req(&req1, req);
3413 	    res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3414 	    if (res == 0) {
3415 		req->sym_out = req1.sym_out;
3416 		req->defobj_out = req1.defobj_out;
3417 	    }
3418 	    return (res);
3419 	}
3420 	if (obj->needed_aux_filtees != NULL) {
3421 	    load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3422 	    donelist_init(&donelist);
3423 	    symlook_init_from_req(&req1, req);
3424 	    res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3425 	    if (res == 0) {
3426 		req->sym_out = req1.sym_out;
3427 		req->defobj_out = req1.defobj_out;
3428 		return (res);
3429 	    }
3430 	}
3431     }
3432     return (mres);
3433 }
3434 
3435 static int
3436 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3437 {
3438     unsigned long symnum;
3439     const Elf_Sym *vsymp;
3440     Elf_Versym verndx;
3441     int vcount;
3442 
3443     if (obj->buckets == NULL)
3444 	return (ESRCH);
3445 
3446     vsymp = NULL;
3447     vcount = 0;
3448     symnum = obj->buckets[req->hash % obj->nbuckets];
3449 
3450     for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3451 	const Elf_Sym *symp;
3452 	const char *strp;
3453 
3454 	if (symnum >= obj->nchains)
3455 	    return (ESRCH);	/* Bad object */
3456 
3457 	symp = obj->symtab + symnum;
3458 	strp = obj->strtab + symp->st_name;
3459 
3460 	switch (ELF_ST_TYPE(symp->st_info)) {
3461 	case STT_FUNC:
3462 	case STT_NOTYPE:
3463 	case STT_OBJECT:
3464 	case STT_GNU_IFUNC:
3465 	    if (symp->st_value == 0)
3466 		continue;
3467 		/* fallthrough */
3468 	case STT_TLS:
3469 	    if (symp->st_shndx != SHN_UNDEF)
3470 		break;
3471 	    else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3472 		 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3473 		break;
3474 		/* fallthrough */
3475 	default:
3476 	    continue;
3477 	}
3478 	if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3479 	    continue;
3480 
3481 	if (req->ventry == NULL) {
3482 	    if (obj->versyms != NULL) {
3483 		verndx = VER_NDX(obj->versyms[symnum]);
3484 		if (verndx > obj->vernum) {
3485 		    _rtld_error("%s: symbol %s references wrong version %d",
3486 			obj->path, obj->strtab + symnum, verndx);
3487 		    continue;
3488 		}
3489 		/*
3490 		 * If we are not called from dlsym (i.e. this is a normal
3491 		 * relocation from unversioned binary), accept the symbol
3492 		 * immediately if it happens to have first version after
3493 		 * this shared object became versioned. Otherwise, if
3494 		 * symbol is versioned and not hidden, remember it. If it
3495 		 * is the only symbol with this name exported by the
3496 		 * shared object, it will be returned as a match at the
3497 		 * end of the function. If symbol is global (verndx < 2)
3498 		 * accept it unconditionally.
3499 		 */
3500 		if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3501 		  verndx == VER_NDX_GIVEN) {
3502 		    req->sym_out = symp;
3503 		    req->defobj_out = obj;
3504 		    return (0);
3505 		}
3506 		else if (verndx >= VER_NDX_GIVEN) {
3507 		    if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3508 			if (vsymp == NULL)
3509 			    vsymp = symp;
3510 			vcount ++;
3511 		    }
3512 		    continue;
3513 		}
3514 	    }
3515 	    req->sym_out = symp;
3516 	    req->defobj_out = obj;
3517 	    return (0);
3518 	} else {
3519 	    if (obj->versyms == NULL) {
3520 		if (object_match_name(obj, req->ventry->name)) {
3521 		    _rtld_error("%s: object %s should provide version %s for "
3522 			"symbol %s", obj_rtld.path, obj->path,
3523 			req->ventry->name, obj->strtab + symnum);
3524 		    continue;
3525 		}
3526 	    } else {
3527 		verndx = VER_NDX(obj->versyms[symnum]);
3528 		if (verndx > obj->vernum) {
3529 		    _rtld_error("%s: symbol %s references wrong version %d",
3530 			obj->path, obj->strtab + symnum, verndx);
3531 		    continue;
3532 		}
3533 		if (obj->vertab[verndx].hash != req->ventry->hash ||
3534 		    strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3535 		    /*
3536 		     * Version does not match. Look if this is a global symbol
3537 		     * and if it is not hidden. If global symbol (verndx < 2)
3538 		     * is available, use it. Do not return symbol if we are
3539 		     * called by dlvsym, because dlvsym looks for a specific
3540 		     * version and default one is not what dlvsym wants.
3541 		     */
3542 		    if ((req->flags & SYMLOOK_DLSYM) ||
3543 			(obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3544 			(verndx >= VER_NDX_GIVEN))
3545 			continue;
3546 		}
3547 	    }
3548 	    req->sym_out = symp;
3549 	    req->defobj_out = obj;
3550 	    return (0);
3551 	}
3552     }
3553     if (vcount == 1) {
3554 	req->sym_out = vsymp;
3555 	req->defobj_out = obj;
3556 	return (0);
3557     }
3558     return (ESRCH);
3559 }
3560 
3561 static void
3562 trace_loaded_objects(Obj_Entry *obj)
3563 {
3564     const char *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3565     int		c;
3566 
3567     if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3568 	main_local = "";
3569 
3570     if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3571 	fmt1 = "\t%o => %p (%x)\n";
3572 
3573     if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3574 	fmt2 = "\t%o (%x)\n";
3575 
3576     list_containers = _getenv_ld("LD_TRACE_LOADED_OBJECTS_ALL");
3577 
3578     for (; obj; obj = obj->next) {
3579 	Needed_Entry		*needed;
3580 	char			*name, *path;
3581 	bool			is_lib;
3582 
3583 	if (list_containers && obj->needed != NULL)
3584 	    rtld_printf("%s:\n", obj->path);
3585 	for (needed = obj->needed; needed; needed = needed->next) {
3586 	    if (needed->obj != NULL) {
3587 		if (needed->obj->traced && !list_containers)
3588 		    continue;
3589 		needed->obj->traced = true;
3590 		path = needed->obj->path;
3591 	    } else
3592 		path = "not found";
3593 
3594 	    name = (char *)obj->strtab + needed->name;
3595 	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
3596 
3597 	    fmt = is_lib ? fmt1 : fmt2;
3598 	    while ((c = *fmt++) != '\0') {
3599 		switch (c) {
3600 		default:
3601 		    rtld_putchar(c);
3602 		    continue;
3603 		case '\\':
3604 		    switch (c = *fmt) {
3605 		    case '\0':
3606 			continue;
3607 		    case 'n':
3608 			rtld_putchar('\n');
3609 			break;
3610 		    case 't':
3611 			rtld_putchar('\t');
3612 			break;
3613 		    }
3614 		    break;
3615 		case '%':
3616 		    switch (c = *fmt) {
3617 		    case '\0':
3618 			continue;
3619 		    case '%':
3620 		    default:
3621 			rtld_putchar(c);
3622 			break;
3623 		    case 'A':
3624 			rtld_putstr(main_local);
3625 			break;
3626 		    case 'a':
3627 			rtld_putstr(obj_main->path);
3628 			break;
3629 		    case 'o':
3630 			rtld_putstr(name);
3631 			break;
3632 		    case 'p':
3633 			rtld_putstr(path);
3634 			break;
3635 		    case 'x':
3636 			rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3637 			  0);
3638 			break;
3639 		    }
3640 		    break;
3641 		}
3642 		++fmt;
3643 	    }
3644 	}
3645     }
3646 }
3647 
3648 /*
3649  * Unload a dlopened object and its dependencies from memory and from
3650  * our data structures.  It is assumed that the DAG rooted in the
3651  * object has already been unreferenced, and that the object has a
3652  * reference count of 0.
3653  */
3654 static void
3655 unload_object(Obj_Entry *root)
3656 {
3657     Obj_Entry *obj;
3658     Obj_Entry **linkp;
3659 
3660     assert(root->refcount == 0);
3661 
3662     /*
3663      * Pass over the DAG removing unreferenced objects from
3664      * appropriate lists.
3665      */
3666     unlink_object(root);
3667 
3668     /* Unmap all objects that are no longer referenced. */
3669     linkp = &obj_list->next;
3670     while ((obj = *linkp) != NULL) {
3671 	if (obj->refcount == 0) {
3672 	    LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3673 		obj->path);
3674 	    dbg("unloading \"%s\"", obj->path);
3675 	    unload_filtees(root);
3676 	    munmap(obj->mapbase, obj->mapsize);
3677 	    linkmap_delete(obj);
3678 	    *linkp = obj->next;
3679 	    obj_count--;
3680 	    obj_free(obj);
3681 	} else
3682 	    linkp = &obj->next;
3683     }
3684     obj_tail = linkp;
3685 }
3686 
3687 static void
3688 unlink_object(Obj_Entry *root)
3689 {
3690     Objlist_Entry *elm;
3691 
3692     if (root->refcount == 0) {
3693 	/* Remove the object from the RTLD_GLOBAL list. */
3694 	objlist_remove(&list_global, root);
3695 
3696     	/* Remove the object from all objects' DAG lists. */
3697 	STAILQ_FOREACH(elm, &root->dagmembers, link) {
3698 	    objlist_remove(&elm->obj->dldags, root);
3699 	    if (elm->obj != root)
3700 		unlink_object(elm->obj);
3701 	}
3702     }
3703 }
3704 
3705 static void
3706 ref_dag(Obj_Entry *root)
3707 {
3708     Objlist_Entry *elm;
3709 
3710     assert(root->dag_inited);
3711     STAILQ_FOREACH(elm, &root->dagmembers, link)
3712 	elm->obj->refcount++;
3713 }
3714 
3715 static void
3716 unref_dag(Obj_Entry *root)
3717 {
3718     Objlist_Entry *elm;
3719 
3720     assert(root->dag_inited);
3721     STAILQ_FOREACH(elm, &root->dagmembers, link)
3722 	elm->obj->refcount--;
3723 }
3724 
3725 /*
3726  * Common code for MD __tls_get_addr().
3727  */
3728 void *
3729 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3730 {
3731     Elf_Addr* dtv = *dtvp;
3732     RtldLockState lockstate;
3733 
3734     /* Check dtv generation in case new modules have arrived */
3735     if (dtv[0] != tls_dtv_generation) {
3736 	Elf_Addr* newdtv;
3737 	int to_copy;
3738 
3739 	wlock_acquire(rtld_bind_lock, &lockstate);
3740 	newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3741 	to_copy = dtv[1];
3742 	if (to_copy > tls_max_index)
3743 	    to_copy = tls_max_index;
3744 	memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3745 	newdtv[0] = tls_dtv_generation;
3746 	newdtv[1] = tls_max_index;
3747 	free(dtv);
3748 	lock_release(rtld_bind_lock, &lockstate);
3749 	dtv = *dtvp = newdtv;
3750     }
3751 
3752     /* Dynamically allocate module TLS if necessary */
3753     if (!dtv[index + 1]) {
3754 	/* Signal safe, wlock will block out signals. */
3755 	wlock_acquire(rtld_bind_lock, &lockstate);
3756 	if (!dtv[index + 1])
3757 	    dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3758 	lock_release(rtld_bind_lock, &lockstate);
3759     }
3760     return (void*) (dtv[index + 1] + offset);
3761 }
3762 
3763 #if defined(RTLD_STATIC_TLS_VARIANT_II)
3764 
3765 /*
3766  * Allocate the static TLS area.  Return a pointer to the TCB.  The
3767  * static area is based on negative offsets relative to the tcb.
3768  *
3769  * The TCB contains an errno pointer for the system call layer, but because
3770  * we are the RTLD we really have no idea how the caller was compiled so
3771  * the information has to be passed in.  errno can either be:
3772  *
3773  *	type 0	errno is a simple non-TLS global pointer.
3774  *		(special case for e.g. libc_rtld)
3775  *	type 1	errno accessed by GOT entry	(dynamically linked programs)
3776  *	type 2	errno accessed by %gs:OFFSET	(statically linked programs)
3777  */
3778 struct tls_tcb *
3779 allocate_tls(Obj_Entry *objs)
3780 {
3781     Obj_Entry *obj;
3782     size_t data_size;
3783     size_t dtv_size;
3784     struct tls_tcb *tcb;
3785     Elf_Addr *dtv;
3786     Elf_Addr addr;
3787 
3788     /*
3789      * Allocate the new TCB.  static TLS storage is placed just before the
3790      * TCB to support the %gs:OFFSET (negative offset) model.
3791      */
3792     data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3793 		~RTLD_STATIC_TLS_ALIGN_MASK;
3794     tcb = malloc(data_size + sizeof(*tcb));
3795     tcb = (void *)((char *)tcb + data_size);	/* actual tcb location */
3796 
3797     dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
3798     dtv = malloc(dtv_size);
3799     bzero(dtv, dtv_size);
3800 
3801 #ifdef RTLD_TCB_HAS_SELF_POINTER
3802     tcb->tcb_self = tcb;
3803 #endif
3804     tcb->tcb_dtv = dtv;
3805     tcb->tcb_pthread = NULL;
3806 
3807     dtv[0] = tls_dtv_generation;
3808     dtv[1] = tls_max_index;
3809 
3810     for (obj = objs; obj; obj = obj->next) {
3811 	if (obj->tlsoffset) {
3812 	    addr = (Elf_Addr)tcb - obj->tlsoffset;
3813 	    memset((void *)(addr + obj->tlsinitsize),
3814 		   0, obj->tlssize - obj->tlsinitsize);
3815 	    if (obj->tlsinit)
3816 		memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3817 	    dtv[obj->tlsindex + 1] = addr;
3818 	}
3819     }
3820     return(tcb);
3821 }
3822 
3823 void
3824 free_tls(struct tls_tcb *tcb)
3825 {
3826     Elf_Addr *dtv;
3827     int dtv_size, i;
3828     Elf_Addr tls_start, tls_end;
3829     size_t data_size;
3830 
3831     data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
3832 		~RTLD_STATIC_TLS_ALIGN_MASK;
3833 
3834     dtv = tcb->tcb_dtv;
3835     dtv_size = dtv[1];
3836     tls_end = (Elf_Addr)tcb;
3837     tls_start = (Elf_Addr)tcb - data_size;
3838     for (i = 0; i < dtv_size; i++) {
3839 	if (dtv[i+2] != 0 && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
3840 	    free((void *)dtv[i+2]);
3841 	}
3842     }
3843 
3844     free((void*) tls_start);
3845 }
3846 
3847 #else
3848 #error "Unsupported TLS layout"
3849 #endif
3850 
3851 /*
3852  * Allocate TLS block for module with given index.
3853  */
3854 void *
3855 allocate_module_tls(int index)
3856 {
3857     Obj_Entry* obj;
3858     char* p;
3859 
3860     for (obj = obj_list; obj; obj = obj->next) {
3861 	if (obj->tlsindex == index)
3862 	    break;
3863     }
3864     if (!obj) {
3865 	_rtld_error("Can't find module with TLS index %d", index);
3866 	die();
3867     }
3868 
3869     p = malloc(obj->tlssize);
3870     if (p == NULL) {
3871 	_rtld_error("Cannot allocate TLS block for index %d", index);
3872 	die();
3873     }
3874     memcpy(p, obj->tlsinit, obj->tlsinitsize);
3875     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3876 
3877     return p;
3878 }
3879 
3880 bool
3881 allocate_tls_offset(Obj_Entry *obj)
3882 {
3883     size_t off;
3884 
3885     if (obj->tls_done)
3886 	return true;
3887 
3888     if (obj->tlssize == 0) {
3889 	obj->tls_done = true;
3890 	return true;
3891     }
3892 
3893     if (obj->tlsindex == 1)
3894 	off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3895     else
3896 	off = calculate_tls_offset(tls_last_offset, tls_last_size,
3897 				   obj->tlssize, obj->tlsalign);
3898 
3899     /*
3900      * If we have already fixed the size of the static TLS block, we
3901      * must stay within that size. When allocating the static TLS, we
3902      * leave a small amount of space spare to be used for dynamically
3903      * loading modules which use static TLS.
3904      */
3905     if (tls_static_space) {
3906 	if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3907 	    return false;
3908     }
3909 
3910     tls_last_offset = obj->tlsoffset = off;
3911     tls_last_size = obj->tlssize;
3912     obj->tls_done = true;
3913 
3914     return true;
3915 }
3916 
3917 void
3918 free_tls_offset(Obj_Entry *obj)
3919 {
3920 #ifdef RTLD_STATIC_TLS_VARIANT_II
3921     /*
3922      * If we were the last thing to allocate out of the static TLS
3923      * block, we give our space back to the 'allocator'. This is a
3924      * simplistic workaround to allow libGL.so.1 to be loaded and
3925      * unloaded multiple times. We only handle the Variant II
3926      * mechanism for now - this really needs a proper allocator.
3927      */
3928     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3929 	== calculate_tls_end(tls_last_offset, tls_last_size)) {
3930 	tls_last_offset -= obj->tlssize;
3931 	tls_last_size = 0;
3932     }
3933 #endif
3934 }
3935 
3936 struct tls_tcb *
3937 _rtld_allocate_tls(void)
3938 {
3939     struct tls_tcb *new_tcb;
3940     RtldLockState lockstate;
3941 
3942     wlock_acquire(rtld_bind_lock, &lockstate);
3943     new_tcb = allocate_tls(obj_list);
3944     lock_release(rtld_bind_lock, &lockstate);
3945     return (new_tcb);
3946 }
3947 
3948 void
3949 _rtld_free_tls(struct tls_tcb *tcb)
3950 {
3951     RtldLockState lockstate;
3952 
3953     wlock_acquire(rtld_bind_lock, &lockstate);
3954     free_tls(tcb);
3955     lock_release(rtld_bind_lock, &lockstate);
3956 }
3957 
3958 static void
3959 object_add_name(Obj_Entry *obj, const char *name)
3960 {
3961     Name_Entry *entry;
3962     size_t len;
3963 
3964     len = strlen(name);
3965     entry = malloc(sizeof(Name_Entry) + len);
3966 
3967     if (entry != NULL) {
3968 	strcpy(entry->name, name);
3969 	STAILQ_INSERT_TAIL(&obj->names, entry, link);
3970     }
3971 }
3972 
3973 static int
3974 object_match_name(const Obj_Entry *obj, const char *name)
3975 {
3976     Name_Entry *entry;
3977 
3978     STAILQ_FOREACH(entry, &obj->names, link) {
3979 	if (strcmp(name, entry->name) == 0)
3980 	    return (1);
3981     }
3982     return (0);
3983 }
3984 
3985 static Obj_Entry *
3986 locate_dependency(const Obj_Entry *obj, const char *name)
3987 {
3988     const Objlist_Entry *entry;
3989     const Needed_Entry *needed;
3990 
3991     STAILQ_FOREACH(entry, &list_main, link) {
3992 	if (object_match_name(entry->obj, name))
3993 	    return entry->obj;
3994     }
3995 
3996     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3997 	if (strcmp(obj->strtab + needed->name, name) == 0 ||
3998 	  (needed->obj != NULL && object_match_name(needed->obj, name))) {
3999 	    /*
4000 	     * If there is DT_NEEDED for the name we are looking for,
4001 	     * we are all set.  Note that object might not be found if
4002 	     * dependency was not loaded yet, so the function can
4003 	     * return NULL here.  This is expected and handled
4004 	     * properly by the caller.
4005 	     */
4006 	    return (needed->obj);
4007 	}
4008     }
4009     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4010 	obj->path, name);
4011     die();
4012 }
4013 
4014 static int
4015 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4016     const Elf_Vernaux *vna)
4017 {
4018     const Elf_Verdef *vd;
4019     const char *vername;
4020 
4021     vername = refobj->strtab + vna->vna_name;
4022     vd = depobj->verdef;
4023     if (vd == NULL) {
4024 	_rtld_error("%s: version %s required by %s not defined",
4025 	    depobj->path, vername, refobj->path);
4026 	return (-1);
4027     }
4028     for (;;) {
4029 	if (vd->vd_version != VER_DEF_CURRENT) {
4030 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4031 		depobj->path, vd->vd_version);
4032 	    return (-1);
4033 	}
4034 	if (vna->vna_hash == vd->vd_hash) {
4035 	    const Elf_Verdaux *aux = (const Elf_Verdaux *)
4036 		((char *)vd + vd->vd_aux);
4037 	    if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4038 		return (0);
4039 	}
4040 	if (vd->vd_next == 0)
4041 	    break;
4042 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4043     }
4044     if (vna->vna_flags & VER_FLG_WEAK)
4045 	return (0);
4046     _rtld_error("%s: version %s required by %s not found",
4047 	depobj->path, vername, refobj->path);
4048     return (-1);
4049 }
4050 
4051 static int
4052 rtld_verify_object_versions(Obj_Entry *obj)
4053 {
4054     const Elf_Verneed *vn;
4055     const Elf_Verdef  *vd;
4056     const Elf_Verdaux *vda;
4057     const Elf_Vernaux *vna;
4058     const Obj_Entry *depobj;
4059     int maxvernum, vernum;
4060 
4061     maxvernum = 0;
4062     /*
4063      * Walk over defined and required version records and figure out
4064      * max index used by any of them. Do very basic sanity checking
4065      * while there.
4066      */
4067     vn = obj->verneed;
4068     while (vn != NULL) {
4069 	if (vn->vn_version != VER_NEED_CURRENT) {
4070 	    _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4071 		obj->path, vn->vn_version);
4072 	    return (-1);
4073 	}
4074 	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4075 	for (;;) {
4076 	    vernum = VER_NEED_IDX(vna->vna_other);
4077 	    if (vernum > maxvernum)
4078 		maxvernum = vernum;
4079 	    if (vna->vna_next == 0)
4080 		 break;
4081 	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4082 	}
4083 	if (vn->vn_next == 0)
4084 	    break;
4085 	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4086     }
4087 
4088     vd = obj->verdef;
4089     while (vd != NULL) {
4090 	if (vd->vd_version != VER_DEF_CURRENT) {
4091 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4092 		obj->path, vd->vd_version);
4093 	    return (-1);
4094 	}
4095 	vernum = VER_DEF_IDX(vd->vd_ndx);
4096 	if (vernum > maxvernum)
4097 		maxvernum = vernum;
4098 	if (vd->vd_next == 0)
4099 	    break;
4100 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4101     }
4102 
4103     if (maxvernum == 0)
4104 	return (0);
4105 
4106     /*
4107      * Store version information in array indexable by version index.
4108      * Verify that object version requirements are satisfied along the
4109      * way.
4110      */
4111     obj->vernum = maxvernum + 1;
4112     obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
4113 
4114     vd = obj->verdef;
4115     while (vd != NULL) {
4116 	if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4117 	    vernum = VER_DEF_IDX(vd->vd_ndx);
4118 	    assert(vernum <= maxvernum);
4119 	    vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4120 	    obj->vertab[vernum].hash = vd->vd_hash;
4121 	    obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4122 	    obj->vertab[vernum].file = NULL;
4123 	    obj->vertab[vernum].flags = 0;
4124 	}
4125 	if (vd->vd_next == 0)
4126 	    break;
4127 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4128     }
4129 
4130     vn = obj->verneed;
4131     while (vn != NULL) {
4132 	depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4133 	if (depobj == NULL)
4134 	    return (-1);
4135 	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4136 	for (;;) {
4137 	    if (check_object_provided_version(obj, depobj, vna))
4138 		return (-1);
4139 	    vernum = VER_NEED_IDX(vna->vna_other);
4140 	    assert(vernum <= maxvernum);
4141 	    obj->vertab[vernum].hash = vna->vna_hash;
4142 	    obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4143 	    obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4144 	    obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4145 		VER_INFO_HIDDEN : 0;
4146 	    if (vna->vna_next == 0)
4147 		 break;
4148 	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4149 	}
4150 	if (vn->vn_next == 0)
4151 	    break;
4152 	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4153     }
4154     return 0;
4155 }
4156 
4157 static int
4158 rtld_verify_versions(const Objlist *objlist)
4159 {
4160     Objlist_Entry *entry;
4161     int rc;
4162 
4163     rc = 0;
4164     STAILQ_FOREACH(entry, objlist, link) {
4165 	/*
4166 	 * Skip dummy objects or objects that have their version requirements
4167 	 * already checked.
4168 	 */
4169 	if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4170 	    continue;
4171 	if (rtld_verify_object_versions(entry->obj) == -1) {
4172 	    rc = -1;
4173 	    if (ld_tracing == NULL)
4174 		break;
4175 	}
4176     }
4177     if (rc == 0 || ld_tracing != NULL)
4178 	rc = rtld_verify_object_versions(&obj_rtld);
4179     return rc;
4180 }
4181 
4182 const Ver_Entry *
4183 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4184 {
4185     Elf_Versym vernum;
4186 
4187     if (obj->vertab) {
4188 	vernum = VER_NDX(obj->versyms[symnum]);
4189 	if (vernum >= obj->vernum) {
4190 	    _rtld_error("%s: symbol %s has wrong verneed value %d",
4191 		obj->path, obj->strtab + symnum, vernum);
4192 	} else if (obj->vertab[vernum].hash != 0) {
4193 	    return &obj->vertab[vernum];
4194 	}
4195     }
4196     return NULL;
4197 }
4198 
4199 int
4200 _rtld_get_stack_prot(void)
4201 {
4202 
4203 	return (stack_prot);
4204 }
4205 
4206 static void
4207 map_stacks_exec(RtldLockState *lockstate)
4208 {
4209 	return;
4210 	/*
4211 	 * Stack protection must be implemented in the kernel before the dynamic
4212 	 * linker can handle PT_GNU_STACK sections.
4213 	 * The following is the FreeBSD implementation of map_stacks_exec()
4214 	 * void (*thr_map_stacks_exec)(void);
4215 	 *
4216 	 * if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4217 	 *     return;
4218 	 * thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4219 	 *     get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4220 	 * if (thr_map_stacks_exec != NULL) {
4221 	 *     stack_prot |= PROT_EXEC;
4222 	 *     thr_map_stacks_exec();
4223 	 * }
4224 	 */
4225 }
4226 
4227 void
4228 symlook_init(SymLook *dst, const char *name)
4229 {
4230 
4231 	bzero(dst, sizeof(*dst));
4232 	dst->name = name;
4233 	dst->hash = elf_hash(name);
4234 }
4235 
4236 static void
4237 symlook_init_from_req(SymLook *dst, const SymLook *src)
4238 {
4239 
4240 	dst->name = src->name;
4241 	dst->hash = src->hash;
4242 	dst->ventry = src->ventry;
4243 	dst->flags = src->flags;
4244 	dst->defobj_out = NULL;
4245 	dst->sym_out = NULL;
4246 	dst->lockstate = src->lockstate;
4247 }
4248 
4249 #ifdef ENABLE_OSRELDATE
4250 /*
4251  * Overrides for libc_pic-provided functions.
4252  */
4253 
4254 int
4255 __getosreldate(void)
4256 {
4257 	size_t len;
4258 	int oid[2];
4259 	int error, osrel;
4260 
4261 	if (osreldate != 0)
4262 		return (osreldate);
4263 
4264 	oid[0] = CTL_KERN;
4265 	oid[1] = KERN_OSRELDATE;
4266 	osrel = 0;
4267 	len = sizeof(osrel);
4268 	error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4269 	if (error == 0 && osrel > 0 && len == sizeof(osrel))
4270 		osreldate = osrel;
4271 	return (osreldate);
4272 }
4273 #endif
4274 
4275 /*
4276  * No unresolved symbols for rtld.
4277  */
4278 void
4279 __pthread_cxa_finalize(struct dl_phdr_info *a)
4280 {
4281 }
4282