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