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