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