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