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