]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - libexec/rtld-elf/rtld.c
MFC r239253: Pospone the DF_1_NODELETE processing until object DAG is
[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 static void
1593 process_nodelete(Obj_Entry *root)
1594 {
1595         const Objlist_Entry *elm;
1596
1597         /*
1598          * Walk over object DAG and process every dependent object that
1599          * is marked as DF_1_NODELETE. They need to grow their own DAG,
1600          * which then should have its reference upped separately.
1601          */
1602         STAILQ_FOREACH(elm, &root->dagmembers, link) {
1603                 if (elm->obj != NULL && elm->obj->z_nodelete &&
1604                     !elm->obj->ref_nodel) {
1605                         dbg("obj %s nodelete", elm->obj->path);
1606                         init_dag(elm->obj);
1607                         ref_dag(elm->obj);
1608                         elm->obj->ref_nodel = true;
1609                 }
1610         }
1611 }
1612 /*
1613  * Initialize the dynamic linker.  The argument is the address at which
1614  * the dynamic linker has been mapped into memory.  The primary task of
1615  * this function is to relocate the dynamic linker.
1616  */
1617 static void
1618 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1619 {
1620     Obj_Entry objtmp;   /* Temporary rtld object */
1621     const Elf_Dyn *dyn_rpath;
1622     const Elf_Dyn *dyn_soname;
1623
1624     /*
1625      * Conjure up an Obj_Entry structure for the dynamic linker.
1626      *
1627      * The "path" member can't be initialized yet because string constants
1628      * cannot yet be accessed. Below we will set it correctly.
1629      */
1630     memset(&objtmp, 0, sizeof(objtmp));
1631     objtmp.path = NULL;
1632     objtmp.rtld = true;
1633     objtmp.mapbase = mapbase;
1634 #ifdef PIC
1635     objtmp.relocbase = mapbase;
1636 #endif
1637     if (RTLD_IS_DYNAMIC()) {
1638         objtmp.dynamic = rtld_dynamic(&objtmp);
1639         digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1640         assert(objtmp.needed == NULL);
1641 #if !defined(__mips__)
1642         /* MIPS has a bogus DT_TEXTREL. */
1643         assert(!objtmp.textrel);
1644 #endif
1645
1646         /*
1647          * Temporarily put the dynamic linker entry into the object list, so
1648          * that symbols can be found.
1649          */
1650
1651         relocate_objects(&objtmp, true, &objtmp, 0, NULL);
1652     }
1653
1654     /* Initialize the object list. */
1655     obj_tail = &obj_list;
1656
1657     /* Now that non-local variables can be accesses, copy out obj_rtld. */
1658     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1659
1660     if (aux_info[AT_PAGESZ] != NULL)
1661             pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1662     if (aux_info[AT_OSRELDATE] != NULL)
1663             osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1664
1665     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1666
1667     /* Replace the path with a dynamically allocated copy. */
1668     obj_rtld.path = xstrdup(PATH_RTLD);
1669
1670     r_debug.r_brk = r_debug_state;
1671     r_debug.r_state = RT_CONSISTENT;
1672 }
1673
1674 /*
1675  * Add the init functions from a needed object list (and its recursive
1676  * needed objects) to "list".  This is not used directly; it is a helper
1677  * function for initlist_add_objects().  The write lock must be held
1678  * when this function is called.
1679  */
1680 static void
1681 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1682 {
1683     /* Recursively process the successor needed objects. */
1684     if (needed->next != NULL)
1685         initlist_add_neededs(needed->next, list);
1686
1687     /* Process the current needed object. */
1688     if (needed->obj != NULL)
1689         initlist_add_objects(needed->obj, &needed->obj->next, list);
1690 }
1691
1692 /*
1693  * Scan all of the DAGs rooted in the range of objects from "obj" to
1694  * "tail" and add their init functions to "list".  This recurses over
1695  * the DAGs and ensure the proper init ordering such that each object's
1696  * needed libraries are initialized before the object itself.  At the
1697  * same time, this function adds the objects to the global finalization
1698  * list "list_fini" in the opposite order.  The write lock must be
1699  * held when this function is called.
1700  */
1701 static void
1702 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1703 {
1704
1705     if (obj->init_scanned || obj->init_done)
1706         return;
1707     obj->init_scanned = true;
1708
1709     /* Recursively process the successor objects. */
1710     if (&obj->next != tail)
1711         initlist_add_objects(obj->next, tail, list);
1712
1713     /* Recursively process the needed objects. */
1714     if (obj->needed != NULL)
1715         initlist_add_neededs(obj->needed, list);
1716     if (obj->needed_filtees != NULL)
1717         initlist_add_neededs(obj->needed_filtees, list);
1718     if (obj->needed_aux_filtees != NULL)
1719         initlist_add_neededs(obj->needed_aux_filtees, list);
1720
1721     /* Add the object to the init list. */
1722     if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL ||
1723       obj->init_array != (Elf_Addr)NULL)
1724         objlist_push_tail(list, obj);
1725
1726     /* Add the object to the global fini list in the reverse order. */
1727     if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL)
1728       && !obj->on_fini_list) {
1729         objlist_push_head(&list_fini, obj);
1730         obj->on_fini_list = true;
1731     }
1732 }
1733
1734 #ifndef FPTR_TARGET
1735 #define FPTR_TARGET(f)  ((Elf_Addr) (f))
1736 #endif
1737
1738 static void
1739 free_needed_filtees(Needed_Entry *n)
1740 {
1741     Needed_Entry *needed, *needed1;
1742
1743     for (needed = n; needed != NULL; needed = needed->next) {
1744         if (needed->obj != NULL) {
1745             dlclose(needed->obj);
1746             needed->obj = NULL;
1747         }
1748     }
1749     for (needed = n; needed != NULL; needed = needed1) {
1750         needed1 = needed->next;
1751         free(needed);
1752     }
1753 }
1754
1755 static void
1756 unload_filtees(Obj_Entry *obj)
1757 {
1758
1759     free_needed_filtees(obj->needed_filtees);
1760     obj->needed_filtees = NULL;
1761     free_needed_filtees(obj->needed_aux_filtees);
1762     obj->needed_aux_filtees = NULL;
1763     obj->filtees_loaded = false;
1764 }
1765
1766 static void
1767 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
1768     RtldLockState *lockstate)
1769 {
1770
1771     for (; needed != NULL; needed = needed->next) {
1772         needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1773           flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1774           RTLD_LOCAL, lockstate);
1775     }
1776 }
1777
1778 static void
1779 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1780 {
1781
1782     lock_restart_for_upgrade(lockstate);
1783     if (!obj->filtees_loaded) {
1784         load_filtee1(obj, obj->needed_filtees, flags, lockstate);
1785         load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
1786         obj->filtees_loaded = true;
1787     }
1788 }
1789
1790 static int
1791 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1792 {
1793     Obj_Entry *obj1;
1794
1795     for (; needed != NULL; needed = needed->next) {
1796         obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1797           flags & ~RTLD_LO_NOLOAD);
1798         if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1799             return (-1);
1800     }
1801     return (0);
1802 }
1803
1804 /*
1805  * Given a shared object, traverse its list of needed objects, and load
1806  * each of them.  Returns 0 on success.  Generates an error message and
1807  * returns -1 on failure.
1808  */
1809 static int
1810 load_needed_objects(Obj_Entry *first, int flags)
1811 {
1812     Obj_Entry *obj;
1813
1814     for (obj = first;  obj != NULL;  obj = obj->next) {
1815         if (process_needed(obj, obj->needed, flags) == -1)
1816             return (-1);
1817     }
1818     return (0);
1819 }
1820
1821 static int
1822 load_preload_objects(void)
1823 {
1824     char *p = ld_preload;
1825     static const char delim[] = " \t:;";
1826
1827     if (p == NULL)
1828         return 0;
1829
1830     p += strspn(p, delim);
1831     while (*p != '\0') {
1832         size_t len = strcspn(p, delim);
1833         char savech;
1834
1835         savech = p[len];
1836         p[len] = '\0';
1837         if (load_object(p, -1, NULL, 0) == NULL)
1838             return -1;  /* XXX - cleanup */
1839         p[len] = savech;
1840         p += len;
1841         p += strspn(p, delim);
1842     }
1843     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1844     return 0;
1845 }
1846
1847 static const char *
1848 printable_path(const char *path)
1849 {
1850
1851         return (path == NULL ? "<unknown>" : path);
1852 }
1853
1854 /*
1855  * Load a shared object into memory, if it is not already loaded.  The
1856  * object may be specified by name or by user-supplied file descriptor
1857  * fd_u. In the later case, the fd_u descriptor is not closed, but its
1858  * duplicate is.
1859  *
1860  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1861  * on failure.
1862  */
1863 static Obj_Entry *
1864 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1865 {
1866     Obj_Entry *obj;
1867     int fd;
1868     struct stat sb;
1869     char *path;
1870
1871     if (name != NULL) {
1872         for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1873             if (object_match_name(obj, name))
1874                 return (obj);
1875         }
1876
1877         path = find_library(name, refobj);
1878         if (path == NULL)
1879             return (NULL);
1880     } else
1881         path = NULL;
1882
1883     /*
1884      * If we didn't find a match by pathname, or the name is not
1885      * supplied, open the file and check again by device and inode.
1886      * This avoids false mismatches caused by multiple links or ".."
1887      * in pathnames.
1888      *
1889      * To avoid a race, we open the file and use fstat() rather than
1890      * using stat().
1891      */
1892     fd = -1;
1893     if (fd_u == -1) {
1894         if ((fd = open(path, O_RDONLY)) == -1) {
1895             _rtld_error("Cannot open \"%s\"", path);
1896             free(path);
1897             return (NULL);
1898         }
1899     } else {
1900         fd = dup(fd_u);
1901         if (fd == -1) {
1902             _rtld_error("Cannot dup fd");
1903             free(path);
1904             return (NULL);
1905         }
1906     }
1907     if (fstat(fd, &sb) == -1) {
1908         _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1909         close(fd);
1910         free(path);
1911         return NULL;
1912     }
1913     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1914         if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1915             break;
1916     if (obj != NULL && name != NULL) {
1917         object_add_name(obj, name);
1918         free(path);
1919         close(fd);
1920         return obj;
1921     }
1922     if (flags & RTLD_LO_NOLOAD) {
1923         free(path);
1924         close(fd);
1925         return (NULL);
1926     }
1927
1928     /* First use of this object, so we must map it in */
1929     obj = do_load_object(fd, name, path, &sb, flags);
1930     if (obj == NULL)
1931         free(path);
1932     close(fd);
1933
1934     return obj;
1935 }
1936
1937 static Obj_Entry *
1938 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1939   int flags)
1940 {
1941     Obj_Entry *obj;
1942     struct statfs fs;
1943
1944     /*
1945      * but first, make sure that environment variables haven't been
1946      * used to circumvent the noexec flag on a filesystem.
1947      */
1948     if (dangerous_ld_env) {
1949         if (fstatfs(fd, &fs) != 0) {
1950             _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1951             return NULL;
1952         }
1953         if (fs.f_flags & MNT_NOEXEC) {
1954             _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1955             return NULL;
1956         }
1957     }
1958     dbg("loading \"%s\"", printable_path(path));
1959     obj = map_object(fd, printable_path(path), sbp);
1960     if (obj == NULL)
1961         return NULL;
1962
1963     /*
1964      * If DT_SONAME is present in the object, digest_dynamic2 already
1965      * added it to the object names.
1966      */
1967     if (name != NULL)
1968         object_add_name(obj, name);
1969     obj->path = path;
1970     digest_dynamic(obj, 0);
1971     dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path,
1972         obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount);
1973     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1974       RTLD_LO_DLOPEN) {
1975         dbg("refusing to load non-loadable \"%s\"", obj->path);
1976         _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1977         munmap(obj->mapbase, obj->mapsize);
1978         obj_free(obj);
1979         return (NULL);
1980     }
1981
1982     *obj_tail = obj;
1983     obj_tail = &obj->next;
1984     obj_count++;
1985     obj_loads++;
1986     linkmap_add(obj);   /* for GDB & dlinfo() */
1987     max_stack_flags |= obj->stack_flags;
1988
1989     dbg("  %p .. %p: %s", obj->mapbase,
1990          obj->mapbase + obj->mapsize - 1, obj->path);
1991     if (obj->textrel)
1992         dbg("  WARNING: %s has impure text", obj->path);
1993     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1994         obj->path);    
1995
1996     return obj;
1997 }
1998
1999 static Obj_Entry *
2000 obj_from_addr(const void *addr)
2001 {
2002     Obj_Entry *obj;
2003
2004     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2005         if (addr < (void *) obj->mapbase)
2006             continue;
2007         if (addr < (void *) (obj->mapbase + obj->mapsize))
2008             return obj;
2009     }
2010     return NULL;
2011 }
2012
2013 static void
2014 preinit_main(void)
2015 {
2016     Elf_Addr *preinit_addr;
2017     int index;
2018
2019     preinit_addr = (Elf_Addr *)obj_main->preinit_array;
2020     if (preinit_addr == NULL)
2021         return;
2022
2023     for (index = 0; index < obj_main->preinit_array_num; index++) {
2024         if (preinit_addr[index] != 0 && preinit_addr[index] != 1) {
2025             dbg("calling preinit function for %s at %p", obj_main->path,
2026               (void *)preinit_addr[index]);
2027             LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index],
2028               0, 0, obj_main->path);
2029             call_init_pointer(obj_main, preinit_addr[index]);
2030         }
2031     }
2032 }
2033
2034 /*
2035  * Call the finalization functions for each of the objects in "list"
2036  * belonging to the DAG of "root" and referenced once. If NULL "root"
2037  * is specified, every finalization function will be called regardless
2038  * of the reference count and the list elements won't be freed. All of
2039  * the objects are expected to have non-NULL fini functions.
2040  */
2041 static void
2042 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
2043 {
2044     Objlist_Entry *elm;
2045     char *saved_msg;
2046     Elf_Addr *fini_addr;
2047     int index;
2048
2049     assert(root == NULL || root->refcount == 1);
2050
2051     /*
2052      * Preserve the current error message since a fini function might
2053      * call into the dynamic linker and overwrite it.
2054      */
2055     saved_msg = errmsg_save();
2056     do {
2057         STAILQ_FOREACH(elm, list, link) {
2058             if (root != NULL && (elm->obj->refcount != 1 ||
2059               objlist_find(&root->dagmembers, elm->obj) == NULL))
2060                 continue;
2061             /* Remove object from fini list to prevent recursive invocation. */
2062             STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2063             /*
2064              * XXX: If a dlopen() call references an object while the
2065              * fini function is in progress, we might end up trying to
2066              * unload the referenced object in dlclose() or the object
2067              * won't be unloaded although its fini function has been
2068              * called.
2069              */
2070             lock_release(rtld_bind_lock, lockstate);
2071
2072             /*
2073              * It is legal to have both DT_FINI and DT_FINI_ARRAY defined.
2074              * When this happens, DT_FINI_ARRAY is processed first.
2075              */
2076             fini_addr = (Elf_Addr *)elm->obj->fini_array;
2077             if (fini_addr != NULL && elm->obj->fini_array_num > 0) {
2078                 for (index = elm->obj->fini_array_num - 1; index >= 0;
2079                   index--) {
2080                     if (fini_addr[index] != 0 && fini_addr[index] != 1) {
2081                         dbg("calling fini function for %s at %p",
2082                             elm->obj->path, (void *)fini_addr[index]);
2083                         LD_UTRACE(UTRACE_FINI_CALL, elm->obj,
2084                             (void *)fini_addr[index], 0, 0, elm->obj->path);
2085                         call_initfini_pointer(elm->obj, fini_addr[index]);
2086                     }
2087                 }
2088             }
2089             if (elm->obj->fini != (Elf_Addr)NULL) {
2090                 dbg("calling fini function for %s at %p", elm->obj->path,
2091                     (void *)elm->obj->fini);
2092                 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini,
2093                     0, 0, elm->obj->path);
2094                 call_initfini_pointer(elm->obj, elm->obj->fini);
2095             }
2096             wlock_acquire(rtld_bind_lock, lockstate);
2097             /* No need to free anything if process is going down. */
2098             if (root != NULL)
2099                 free(elm);
2100             /*
2101              * We must restart the list traversal after every fini call
2102              * because a dlclose() call from the fini function or from
2103              * another thread might have modified the reference counts.
2104              */
2105             break;
2106         }
2107     } while (elm != NULL);
2108     errmsg_restore(saved_msg);
2109 }
2110
2111 /*
2112  * Call the initialization functions for each of the objects in
2113  * "list".  All of the objects are expected to have non-NULL init
2114  * functions.
2115  */
2116 static void
2117 objlist_call_init(Objlist *list, RtldLockState *lockstate)
2118 {
2119     Objlist_Entry *elm;
2120     Obj_Entry *obj;
2121     char *saved_msg;
2122     Elf_Addr *init_addr;
2123     int index;
2124
2125     /*
2126      * Clean init_scanned flag so that objects can be rechecked and
2127      * possibly initialized earlier if any of vectors called below
2128      * cause the change by using dlopen.
2129      */
2130     for (obj = obj_list;  obj != NULL;  obj = obj->next)
2131         obj->init_scanned = false;
2132
2133     /*
2134      * Preserve the current error message since an init function might
2135      * call into the dynamic linker and overwrite it.
2136      */
2137     saved_msg = errmsg_save();
2138     STAILQ_FOREACH(elm, list, link) {
2139         if (elm->obj->init_done) /* Initialized early. */
2140             continue;
2141         /*
2142          * Race: other thread might try to use this object before current
2143          * one completes the initilization. Not much can be done here
2144          * without better locking.
2145          */
2146         elm->obj->init_done = true;
2147         lock_release(rtld_bind_lock, lockstate);
2148
2149         /*
2150          * It is legal to have both DT_INIT and DT_INIT_ARRAY defined.
2151          * When this happens, DT_INIT is processed first.
2152          */
2153         if (elm->obj->init != (Elf_Addr)NULL) {
2154             dbg("calling init function for %s at %p", elm->obj->path,
2155                 (void *)elm->obj->init);
2156             LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init,
2157                 0, 0, elm->obj->path);
2158             call_initfini_pointer(elm->obj, elm->obj->init);
2159         }
2160         init_addr = (Elf_Addr *)elm->obj->init_array;
2161         if (init_addr != NULL) {
2162             for (index = 0; index < elm->obj->init_array_num; index++) {
2163                 if (init_addr[index] != 0 && init_addr[index] != 1) {
2164                     dbg("calling init function for %s at %p", elm->obj->path,
2165                         (void *)init_addr[index]);
2166                     LD_UTRACE(UTRACE_INIT_CALL, elm->obj,
2167                         (void *)init_addr[index], 0, 0, elm->obj->path);
2168                     call_init_pointer(elm->obj, init_addr[index]);
2169                 }
2170             }
2171         }
2172         wlock_acquire(rtld_bind_lock, lockstate);
2173     }
2174     errmsg_restore(saved_msg);
2175 }
2176
2177 static void
2178 objlist_clear(Objlist *list)
2179 {
2180     Objlist_Entry *elm;
2181
2182     while (!STAILQ_EMPTY(list)) {
2183         elm = STAILQ_FIRST(list);
2184         STAILQ_REMOVE_HEAD(list, link);
2185         free(elm);
2186     }
2187 }
2188
2189 static Objlist_Entry *
2190 objlist_find(Objlist *list, const Obj_Entry *obj)
2191 {
2192     Objlist_Entry *elm;
2193
2194     STAILQ_FOREACH(elm, list, link)
2195         if (elm->obj == obj)
2196             return elm;
2197     return NULL;
2198 }
2199
2200 static void
2201 objlist_init(Objlist *list)
2202 {
2203     STAILQ_INIT(list);
2204 }
2205
2206 static void
2207 objlist_push_head(Objlist *list, Obj_Entry *obj)
2208 {
2209     Objlist_Entry *elm;
2210
2211     elm = NEW(Objlist_Entry);
2212     elm->obj = obj;
2213     STAILQ_INSERT_HEAD(list, elm, link);
2214 }
2215
2216 static void
2217 objlist_push_tail(Objlist *list, Obj_Entry *obj)
2218 {
2219     Objlist_Entry *elm;
2220
2221     elm = NEW(Objlist_Entry);
2222     elm->obj = obj;
2223     STAILQ_INSERT_TAIL(list, elm, link);
2224 }
2225
2226 static void
2227 objlist_remove(Objlist *list, Obj_Entry *obj)
2228 {
2229     Objlist_Entry *elm;
2230
2231     if ((elm = objlist_find(list, obj)) != NULL) {
2232         STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
2233         free(elm);
2234     }
2235 }
2236
2237 /*
2238  * Relocate dag rooted in the specified object.
2239  * Returns 0 on success, or -1 on failure.
2240  */
2241
2242 static int
2243 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj,
2244     int flags, RtldLockState *lockstate)
2245 {
2246         Objlist_Entry *elm;
2247         int error;
2248
2249         error = 0;
2250         STAILQ_FOREACH(elm, &root->dagmembers, link) {
2251                 error = relocate_object(elm->obj, bind_now, rtldobj, flags,
2252                     lockstate);
2253                 if (error == -1)
2254                         break;
2255         }
2256         return (error);
2257 }
2258
2259 /*
2260  * Relocate single object.
2261  * Returns 0 on success, or -1 on failure.
2262  */
2263 static int
2264 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
2265     int flags, RtldLockState *lockstate)
2266 {
2267
2268         if (obj->relocated)
2269                 return (0);
2270         obj->relocated = true;
2271         if (obj != rtldobj)
2272                 dbg("relocating \"%s\"", obj->path);
2273
2274         if (obj->symtab == NULL || obj->strtab == NULL ||
2275             !(obj->valid_hash_sysv || obj->valid_hash_gnu)) {
2276                 _rtld_error("%s: Shared object has no run-time symbol table",
2277                             obj->path);
2278                 return (-1);
2279         }
2280
2281         if (obj->textrel) {
2282                 /* There are relocations to the write-protected text segment. */
2283                 if (mprotect(obj->mapbase, obj->textsize,
2284                     PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
2285                         _rtld_error("%s: Cannot write-enable text segment: %s",
2286                             obj->path, rtld_strerror(errno));
2287                         return (-1);
2288                 }
2289         }
2290
2291         /* Process the non-PLT relocations. */
2292         if (reloc_non_plt(obj, rtldobj, flags, lockstate))
2293                 return (-1);
2294
2295         if (obj->textrel) {     /* Re-protected the text segment. */
2296                 if (mprotect(obj->mapbase, obj->textsize,
2297                     PROT_READ|PROT_EXEC) == -1) {
2298                         _rtld_error("%s: Cannot write-protect text segment: %s",
2299                             obj->path, rtld_strerror(errno));
2300                         return (-1);
2301                 }
2302         }
2303
2304
2305         /* Set the special PLT or GOT entries. */
2306         init_pltgot(obj);
2307
2308         /* Process the PLT relocations. */
2309         if (reloc_plt(obj) == -1)
2310                 return (-1);
2311         /* Relocate the jump slots if we are doing immediate binding. */
2312         if (obj->bind_now || bind_now)
2313                 if (reloc_jmpslots(obj, flags, lockstate) == -1)
2314                         return (-1);
2315
2316         if (obj->relro_size > 0) {
2317                 if (mprotect(obj->relro_page, obj->relro_size,
2318                     PROT_READ) == -1) {
2319                         _rtld_error("%s: Cannot enforce relro protection: %s",
2320                             obj->path, rtld_strerror(errno));
2321                         return (-1);
2322                 }
2323         }
2324
2325         /*
2326          * Set up the magic number and version in the Obj_Entry.  These
2327          * were checked in the crt1.o from the original ElfKit, so we
2328          * set them for backward compatibility.
2329          */
2330         obj->magic = RTLD_MAGIC;
2331         obj->version = RTLD_VERSION;
2332
2333         return (0);
2334 }
2335
2336 /*
2337  * Relocate newly-loaded shared objects.  The argument is a pointer to
2338  * the Obj_Entry for the first such object.  All objects from the first
2339  * to the end of the list of objects are relocated.  Returns 0 on success,
2340  * or -1 on failure.
2341  */
2342 static int
2343 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
2344     int flags, RtldLockState *lockstate)
2345 {
2346         Obj_Entry *obj;
2347         int error;
2348
2349         for (error = 0, obj = first;  obj != NULL;  obj = obj->next) {
2350                 error = relocate_object(obj, bind_now, rtldobj, flags,
2351                     lockstate);
2352                 if (error == -1)
2353                         break;
2354         }
2355         return (error);
2356 }
2357
2358 /*
2359  * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2360  * referencing STT_GNU_IFUNC symbols is postponed till the other
2361  * relocations are done.  The indirect functions specified as
2362  * ifunc are allowed to call other symbols, so we need to have
2363  * objects relocated before asking for resolution from indirects.
2364  *
2365  * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2366  * instead of the usual lazy handling of PLT slots.  It is
2367  * consistent with how GNU does it.
2368  */
2369 static int
2370 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
2371     RtldLockState *lockstate)
2372 {
2373         if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2374                 return (-1);
2375         if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2376             reloc_gnu_ifunc(obj, flags, lockstate) == -1)
2377                 return (-1);
2378         return (0);
2379 }
2380
2381 static int
2382 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
2383     RtldLockState *lockstate)
2384 {
2385         Obj_Entry *obj;
2386
2387         for (obj = first;  obj != NULL;  obj = obj->next) {
2388                 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1)
2389                         return (-1);
2390         }
2391         return (0);
2392 }
2393
2394 static int
2395 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
2396     RtldLockState *lockstate)
2397 {
2398         Objlist_Entry *elm;
2399
2400         STAILQ_FOREACH(elm, list, link) {
2401                 if (resolve_object_ifunc(elm->obj, bind_now, flags,
2402                     lockstate) == -1)
2403                         return (-1);
2404         }
2405         return (0);
2406 }
2407
2408 /*
2409  * Cleanup procedure.  It will be called (by the atexit mechanism) just
2410  * before the process exits.
2411  */
2412 static void
2413 rtld_exit(void)
2414 {
2415     RtldLockState lockstate;
2416
2417     wlock_acquire(rtld_bind_lock, &lockstate);
2418     dbg("rtld_exit()");
2419     objlist_call_fini(&list_fini, NULL, &lockstate);
2420     /* No need to remove the items from the list, since we are exiting. */
2421     if (!libmap_disable)
2422         lm_fini();
2423     lock_release(rtld_bind_lock, &lockstate);
2424 }
2425
2426 static void *
2427 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2428 {
2429 #ifdef COMPAT_32BIT
2430     const char *trans;
2431 #endif
2432     if (path == NULL)
2433         return (NULL);
2434
2435     path += strspn(path, ":;");
2436     while (*path != '\0') {
2437         size_t len;
2438         char  *res;
2439
2440         len = strcspn(path, ":;");
2441 #ifdef COMPAT_32BIT
2442         trans = lm_findn(NULL, path, len);
2443         if (trans)
2444             res = callback(trans, strlen(trans), arg);
2445         else
2446 #endif
2447         res = callback(path, len, arg);
2448
2449         if (res != NULL)
2450             return (res);
2451
2452         path += len;
2453         path += strspn(path, ":;");
2454     }
2455
2456     return (NULL);
2457 }
2458
2459 struct try_library_args {
2460     const char  *name;
2461     size_t       namelen;
2462     char        *buffer;
2463     size_t       buflen;
2464 };
2465
2466 static void *
2467 try_library_path(const char *dir, size_t dirlen, void *param)
2468 {
2469     struct try_library_args *arg;
2470
2471     arg = param;
2472     if (*dir == '/' || trust) {
2473         char *pathname;
2474
2475         if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2476                 return (NULL);
2477
2478         pathname = arg->buffer;
2479         strncpy(pathname, dir, dirlen);
2480         pathname[dirlen] = '/';
2481         strcpy(pathname + dirlen + 1, arg->name);
2482
2483         dbg("  Trying \"%s\"", pathname);
2484         if (access(pathname, F_OK) == 0) {              /* We found it */
2485             pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2486             strcpy(pathname, arg->buffer);
2487             return (pathname);
2488         }
2489     }
2490     return (NULL);
2491 }
2492
2493 static char *
2494 search_library_path(const char *name, const char *path)
2495 {
2496     char *p;
2497     struct try_library_args arg;
2498
2499     if (path == NULL)
2500         return NULL;
2501
2502     arg.name = name;
2503     arg.namelen = strlen(name);
2504     arg.buffer = xmalloc(PATH_MAX);
2505     arg.buflen = PATH_MAX;
2506
2507     p = path_enumerate(path, try_library_path, &arg);
2508
2509     free(arg.buffer);
2510
2511     return (p);
2512 }
2513
2514 int
2515 dlclose(void *handle)
2516 {
2517     Obj_Entry *root;
2518     RtldLockState lockstate;
2519
2520     wlock_acquire(rtld_bind_lock, &lockstate);
2521     root = dlcheck(handle);
2522     if (root == NULL) {
2523         lock_release(rtld_bind_lock, &lockstate);
2524         return -1;
2525     }
2526     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2527         root->path);
2528
2529     /* Unreference the object and its dependencies. */
2530     root->dl_refcount--;
2531
2532     if (root->refcount == 1) {
2533         /*
2534          * The object will be no longer referenced, so we must unload it.
2535          * First, call the fini functions.
2536          */
2537         objlist_call_fini(&list_fini, root, &lockstate);
2538
2539         unref_dag(root);
2540
2541         /* Finish cleaning up the newly-unreferenced objects. */
2542         GDB_STATE(RT_DELETE,&root->linkmap);
2543         unload_object(root);
2544         GDB_STATE(RT_CONSISTENT,NULL);
2545     } else
2546         unref_dag(root);
2547
2548     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2549     lock_release(rtld_bind_lock, &lockstate);
2550     return 0;
2551 }
2552
2553 char *
2554 dlerror(void)
2555 {
2556     char *msg = error_message;
2557     error_message = NULL;
2558     return msg;
2559 }
2560
2561 /*
2562  * This function is deprecated and has no effect.
2563  */
2564 void
2565 dllockinit(void *context,
2566            void *(*lock_create)(void *context),
2567            void (*rlock_acquire)(void *lock),
2568            void (*wlock_acquire)(void *lock),
2569            void (*lock_release)(void *lock),
2570            void (*lock_destroy)(void *lock),
2571            void (*context_destroy)(void *context))
2572 {
2573     static void *cur_context;
2574     static void (*cur_context_destroy)(void *);
2575
2576     /* Just destroy the context from the previous call, if necessary. */
2577     if (cur_context_destroy != NULL)
2578         cur_context_destroy(cur_context);
2579     cur_context = context;
2580     cur_context_destroy = context_destroy;
2581 }
2582
2583 void *
2584 dlopen(const char *name, int mode)
2585 {
2586
2587         return (rtld_dlopen(name, -1, mode));
2588 }
2589
2590 void *
2591 fdlopen(int fd, int mode)
2592 {
2593
2594         return (rtld_dlopen(NULL, fd, mode));
2595 }
2596
2597 static void *
2598 rtld_dlopen(const char *name, int fd, int mode)
2599 {
2600     RtldLockState lockstate;
2601     int lo_flags;
2602
2603     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2604     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2605     if (ld_tracing != NULL) {
2606         rlock_acquire(rtld_bind_lock, &lockstate);
2607         if (sigsetjmp(lockstate.env, 0) != 0)
2608             lock_upgrade(rtld_bind_lock, &lockstate);
2609         environ = (char **)*get_program_var_addr("environ", &lockstate);
2610         lock_release(rtld_bind_lock, &lockstate);
2611     }
2612     lo_flags = RTLD_LO_DLOPEN;
2613     if (mode & RTLD_NODELETE)
2614             lo_flags |= RTLD_LO_NODELETE;
2615     if (mode & RTLD_NOLOAD)
2616             lo_flags |= RTLD_LO_NOLOAD;
2617     if (ld_tracing != NULL)
2618             lo_flags |= RTLD_LO_TRACE;
2619
2620     return (dlopen_object(name, fd, obj_main, lo_flags,
2621       mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
2622 }
2623
2624 static void
2625 dlopen_cleanup(Obj_Entry *obj)
2626 {
2627
2628         obj->dl_refcount--;
2629         unref_dag(obj);
2630         if (obj->refcount == 0)
2631                 unload_object(obj);
2632 }
2633
2634 static Obj_Entry *
2635 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2636     int mode, RtldLockState *lockstate)
2637 {
2638     Obj_Entry **old_obj_tail;
2639     Obj_Entry *obj;
2640     Objlist initlist;
2641     RtldLockState mlockstate;
2642     int result;
2643
2644     objlist_init(&initlist);
2645
2646     if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) {
2647         wlock_acquire(rtld_bind_lock, &mlockstate);
2648         lockstate = &mlockstate;
2649     }
2650     GDB_STATE(RT_ADD,NULL);
2651
2652     old_obj_tail = obj_tail;
2653     obj = NULL;
2654     if (name == NULL && fd == -1) {
2655         obj = obj_main;
2656         obj->refcount++;
2657     } else {
2658         obj = load_object(name, fd, refobj, lo_flags);
2659     }
2660
2661     if (obj) {
2662         obj->dl_refcount++;
2663         if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2664             objlist_push_tail(&list_global, obj);
2665         if (*old_obj_tail != NULL) {            /* We loaded something new. */
2666             assert(*old_obj_tail == obj);
2667             result = load_needed_objects(obj,
2668                 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
2669             init_dag(obj);
2670             ref_dag(obj);
2671             if (result != -1)
2672                 result = rtld_verify_versions(&obj->dagmembers);
2673             if (result != -1 && ld_tracing)
2674                 goto trace;
2675             if (result == -1 || relocate_object_dag(obj,
2676               (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld,
2677               (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2678               lockstate) == -1) {
2679                 dlopen_cleanup(obj);
2680                 obj = NULL;
2681             } else if (lo_flags & RTLD_LO_EARLY) {
2682                 /*
2683                  * Do not call the init functions for early loaded
2684                  * filtees.  The image is still not initialized enough
2685                  * for them to work.
2686                  *
2687                  * Our object is found by the global object list and
2688                  * will be ordered among all init calls done right
2689                  * before transferring control to main.
2690                  */
2691             } else {
2692                 /* Make list of init functions to call. */
2693                 initlist_add_objects(obj, &obj->next, &initlist);
2694             }
2695             /*
2696              * Process all no_delete objects here, given them own
2697              * DAGs to prevent their dependencies from being unloaded.
2698              * This has to be done after we have loaded all of the
2699              * dependencies, so that we do not miss any.
2700              */
2701              process_nodelete(obj);
2702         } else {
2703             /*
2704              * Bump the reference counts for objects on this DAG.  If
2705              * this is the first dlopen() call for the object that was
2706              * already loaded as a dependency, initialize the dag
2707              * starting at it.
2708              */
2709             init_dag(obj);
2710             ref_dag(obj);
2711
2712             if ((lo_flags & RTLD_LO_TRACE) != 0)
2713                 goto trace;
2714         }
2715         if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2716           obj->z_nodelete) && !obj->ref_nodel) {
2717             dbg("obj %s nodelete", obj->path);
2718             ref_dag(obj);
2719             obj->z_nodelete = obj->ref_nodel = true;
2720         }
2721     }
2722
2723     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2724         name);
2725     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2726
2727     if (!(lo_flags & RTLD_LO_EARLY)) {
2728         map_stacks_exec(lockstate);
2729     }
2730
2731     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2732       (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
2733       lockstate) == -1) {
2734         objlist_clear(&initlist);
2735         dlopen_cleanup(obj);
2736         if (lockstate == &mlockstate)
2737             lock_release(rtld_bind_lock, lockstate);
2738         return (NULL);
2739     }
2740
2741     if (!(lo_flags & RTLD_LO_EARLY)) {
2742         /* Call the init functions. */
2743         objlist_call_init(&initlist, lockstate);
2744     }
2745     objlist_clear(&initlist);
2746     if (lockstate == &mlockstate)
2747         lock_release(rtld_bind_lock, lockstate);
2748     return obj;
2749 trace:
2750     trace_loaded_objects(obj);
2751     if (lockstate == &mlockstate)
2752         lock_release(rtld_bind_lock, lockstate);
2753     exit(0);
2754 }
2755
2756 static void *
2757 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2758     int flags)
2759 {
2760     DoneList donelist;
2761     const Obj_Entry *obj, *defobj;
2762     const Elf_Sym *def;
2763     SymLook req;
2764     RtldLockState lockstate;
2765 #ifndef __ia64__
2766     tls_index ti;
2767 #endif
2768     int res;
2769
2770     def = NULL;
2771     defobj = NULL;
2772     symlook_init(&req, name);
2773     req.ventry = ve;
2774     req.flags = flags | SYMLOOK_IN_PLT;
2775     req.lockstate = &lockstate;
2776
2777     rlock_acquire(rtld_bind_lock, &lockstate);
2778     if (sigsetjmp(lockstate.env, 0) != 0)
2779             lock_upgrade(rtld_bind_lock, &lockstate);
2780     if (handle == NULL || handle == RTLD_NEXT ||
2781         handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2782
2783         if ((obj = obj_from_addr(retaddr)) == NULL) {
2784             _rtld_error("Cannot determine caller's shared object");
2785             lock_release(rtld_bind_lock, &lockstate);
2786             return NULL;
2787         }
2788         if (handle == NULL) {   /* Just the caller's shared object. */
2789             res = symlook_obj(&req, obj);
2790             if (res == 0) {
2791                 def = req.sym_out;
2792                 defobj = req.defobj_out;
2793             }
2794         } else if (handle == RTLD_NEXT || /* Objects after caller's */
2795                    handle == RTLD_SELF) { /* ... caller included */
2796             if (handle == RTLD_NEXT)
2797                 obj = obj->next;
2798             for (; obj != NULL; obj = obj->next) {
2799                 res = symlook_obj(&req, obj);
2800                 if (res == 0) {
2801                     if (def == NULL ||
2802                       ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2803                         def = req.sym_out;
2804                         defobj = req.defobj_out;
2805                         if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2806                             break;
2807                     }
2808                 }
2809             }
2810             /*
2811              * Search the dynamic linker itself, and possibly resolve the
2812              * symbol from there.  This is how the application links to
2813              * dynamic linker services such as dlopen.
2814              */
2815             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2816                 res = symlook_obj(&req, &obj_rtld);
2817                 if (res == 0) {
2818                     def = req.sym_out;
2819                     defobj = req.defobj_out;
2820                 }
2821             }
2822         } else {
2823             assert(handle == RTLD_DEFAULT);
2824             res = symlook_default(&req, obj);
2825             if (res == 0) {
2826                 defobj = req.defobj_out;
2827                 def = req.sym_out;
2828             }
2829         }
2830     } else {
2831         if ((obj = dlcheck(handle)) == NULL) {
2832             lock_release(rtld_bind_lock, &lockstate);
2833             return NULL;
2834         }
2835
2836         donelist_init(&donelist);
2837         if (obj->mainprog) {
2838             /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2839             res = symlook_global(&req, &donelist);
2840             if (res == 0) {
2841                 def = req.sym_out;
2842                 defobj = req.defobj_out;
2843             }
2844             /*
2845              * Search the dynamic linker itself, and possibly resolve the
2846              * symbol from there.  This is how the application links to
2847              * dynamic linker services such as dlopen.
2848              */
2849             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2850                 res = symlook_obj(&req, &obj_rtld);
2851                 if (res == 0) {
2852                     def = req.sym_out;
2853                     defobj = req.defobj_out;
2854                 }
2855             }
2856         }
2857         else {
2858             /* Search the whole DAG rooted at the given object. */
2859             res = symlook_list(&req, &obj->dagmembers, &donelist);
2860             if (res == 0) {
2861                 def = req.sym_out;
2862                 defobj = req.defobj_out;
2863             }
2864         }
2865     }
2866
2867     if (def != NULL) {
2868         lock_release(rtld_bind_lock, &lockstate);
2869
2870         /*
2871          * The value required by the caller is derived from the value
2872          * of the symbol. For the ia64 architecture, we need to
2873          * construct a function descriptor which the caller can use to
2874          * call the function with the right 'gp' value. For other
2875          * architectures and for non-functions, the value is simply
2876          * the relocated value of the symbol.
2877          */
2878         if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2879             return (make_function_pointer(def, defobj));
2880         else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2881             return (rtld_resolve_ifunc(defobj, def));
2882         else if (ELF_ST_TYPE(def->st_info) == STT_TLS) {
2883 #ifdef __ia64__
2884             return (__tls_get_addr(defobj->tlsindex, def->st_value));
2885 #else
2886             ti.ti_module = defobj->tlsindex;
2887             ti.ti_offset = def->st_value;
2888             return (__tls_get_addr(&ti));
2889 #endif
2890         } else
2891             return (defobj->relocbase + def->st_value);
2892     }
2893
2894     _rtld_error("Undefined symbol \"%s\"", name);
2895     lock_release(rtld_bind_lock, &lockstate);
2896     return NULL;
2897 }
2898
2899 void *
2900 dlsym(void *handle, const char *name)
2901 {
2902         return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2903             SYMLOOK_DLSYM);
2904 }
2905
2906 dlfunc_t
2907 dlfunc(void *handle, const char *name)
2908 {
2909         union {
2910                 void *d;
2911                 dlfunc_t f;
2912         } rv;
2913
2914         rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2915             SYMLOOK_DLSYM);
2916         return (rv.f);
2917 }
2918
2919 void *
2920 dlvsym(void *handle, const char *name, const char *version)
2921 {
2922         Ver_Entry ventry;
2923
2924         ventry.name = version;
2925         ventry.file = NULL;
2926         ventry.hash = elf_hash(version);
2927         ventry.flags= 0;
2928         return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2929             SYMLOOK_DLSYM);
2930 }
2931
2932 int
2933 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2934 {
2935     const Obj_Entry *obj;
2936     RtldLockState lockstate;
2937
2938     rlock_acquire(rtld_bind_lock, &lockstate);
2939     obj = obj_from_addr(addr);
2940     if (obj == NULL) {
2941         _rtld_error("No shared object contains address");
2942         lock_release(rtld_bind_lock, &lockstate);
2943         return (0);
2944     }
2945     rtld_fill_dl_phdr_info(obj, phdr_info);
2946     lock_release(rtld_bind_lock, &lockstate);
2947     return (1);
2948 }
2949
2950 int
2951 dladdr(const void *addr, Dl_info *info)
2952 {
2953     const Obj_Entry *obj;
2954     const Elf_Sym *def;
2955     void *symbol_addr;
2956     unsigned long symoffset;
2957     RtldLockState lockstate;
2958
2959     rlock_acquire(rtld_bind_lock, &lockstate);
2960     obj = obj_from_addr(addr);
2961     if (obj == NULL) {
2962         _rtld_error("No shared object contains address");
2963         lock_release(rtld_bind_lock, &lockstate);
2964         return 0;
2965     }
2966     info->dli_fname = obj->path;
2967     info->dli_fbase = obj->mapbase;
2968     info->dli_saddr = (void *)0;
2969     info->dli_sname = NULL;
2970
2971     /*
2972      * Walk the symbol list looking for the symbol whose address is
2973      * closest to the address sent in.
2974      */
2975     for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) {
2976         def = obj->symtab + symoffset;
2977
2978         /*
2979          * For skip the symbol if st_shndx is either SHN_UNDEF or
2980          * SHN_COMMON.
2981          */
2982         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2983             continue;
2984
2985         /*
2986          * If the symbol is greater than the specified address, or if it
2987          * is further away from addr than the current nearest symbol,
2988          * then reject it.
2989          */
2990         symbol_addr = obj->relocbase + def->st_value;
2991         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2992             continue;
2993
2994         /* Update our idea of the nearest symbol. */
2995         info->dli_sname = obj->strtab + def->st_name;
2996         info->dli_saddr = symbol_addr;
2997
2998         /* Exact match? */
2999         if (info->dli_saddr == addr)
3000             break;
3001     }
3002     lock_release(rtld_bind_lock, &lockstate);
3003     return 1;
3004 }
3005
3006 int
3007 dlinfo(void *handle, int request, void *p)
3008 {
3009     const Obj_Entry *obj;
3010     RtldLockState lockstate;
3011     int error;
3012
3013     rlock_acquire(rtld_bind_lock, &lockstate);
3014
3015     if (handle == NULL || handle == RTLD_SELF) {
3016         void *retaddr;
3017
3018         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
3019         if ((obj = obj_from_addr(retaddr)) == NULL)
3020             _rtld_error("Cannot determine caller's shared object");
3021     } else
3022         obj = dlcheck(handle);
3023
3024     if (obj == NULL) {
3025         lock_release(rtld_bind_lock, &lockstate);
3026         return (-1);
3027     }
3028
3029     error = 0;
3030     switch (request) {
3031     case RTLD_DI_LINKMAP:
3032         *((struct link_map const **)p) = &obj->linkmap;
3033         break;
3034     case RTLD_DI_ORIGIN:
3035         error = rtld_dirname(obj->path, p);
3036         break;
3037
3038     case RTLD_DI_SERINFOSIZE:
3039     case RTLD_DI_SERINFO:
3040         error = do_search_info(obj, request, (struct dl_serinfo *)p);
3041         break;
3042
3043     default:
3044         _rtld_error("Invalid request %d passed to dlinfo()", request);
3045         error = -1;
3046     }
3047
3048     lock_release(rtld_bind_lock, &lockstate);
3049
3050     return (error);
3051 }
3052
3053 static void
3054 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
3055 {
3056
3057         phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
3058         phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
3059             STAILQ_FIRST(&obj->names)->name : obj->path;
3060         phdr_info->dlpi_phdr = obj->phdr;
3061         phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
3062         phdr_info->dlpi_tls_modid = obj->tlsindex;
3063         phdr_info->dlpi_tls_data = obj->tlsinit;
3064         phdr_info->dlpi_adds = obj_loads;
3065         phdr_info->dlpi_subs = obj_loads - obj_count;
3066 }
3067
3068 int
3069 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
3070 {
3071     struct dl_phdr_info phdr_info;
3072     const Obj_Entry *obj;
3073     RtldLockState bind_lockstate, phdr_lockstate;
3074     int error;
3075
3076     wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
3077     rlock_acquire(rtld_bind_lock, &bind_lockstate);
3078
3079     error = 0;
3080
3081     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
3082         rtld_fill_dl_phdr_info(obj, &phdr_info);
3083         if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
3084                 break;
3085
3086     }
3087     lock_release(rtld_bind_lock, &bind_lockstate);
3088     lock_release(rtld_phdr_lock, &phdr_lockstate);
3089
3090     return (error);
3091 }
3092
3093 struct fill_search_info_args {
3094     int          request;
3095     unsigned int flags;
3096     Dl_serinfo  *serinfo;
3097     Dl_serpath  *serpath;
3098     char        *strspace;
3099 };
3100
3101 static void *
3102 fill_search_info(const char *dir, size_t dirlen, void *param)
3103 {
3104     struct fill_search_info_args *arg;
3105
3106     arg = param;
3107
3108     if (arg->request == RTLD_DI_SERINFOSIZE) {
3109         arg->serinfo->dls_cnt ++;
3110         arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
3111     } else {
3112         struct dl_serpath *s_entry;
3113
3114         s_entry = arg->serpath;
3115         s_entry->dls_name  = arg->strspace;
3116         s_entry->dls_flags = arg->flags;
3117
3118         strncpy(arg->strspace, dir, dirlen);
3119         arg->strspace[dirlen] = '\0';
3120
3121         arg->strspace += dirlen + 1;
3122         arg->serpath++;
3123     }
3124
3125     return (NULL);
3126 }
3127
3128 static int
3129 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
3130 {
3131     struct dl_serinfo _info;
3132     struct fill_search_info_args args;
3133
3134     args.request = RTLD_DI_SERINFOSIZE;
3135     args.serinfo = &_info;
3136
3137     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
3138     _info.dls_cnt  = 0;
3139
3140     path_enumerate(ld_library_path, fill_search_info, &args);
3141     path_enumerate(obj->rpath, fill_search_info, &args);
3142     path_enumerate(gethints(), fill_search_info, &args);
3143     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
3144
3145
3146     if (request == RTLD_DI_SERINFOSIZE) {
3147         info->dls_size = _info.dls_size;
3148         info->dls_cnt = _info.dls_cnt;
3149         return (0);
3150     }
3151
3152     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
3153         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
3154         return (-1);
3155     }
3156
3157     args.request  = RTLD_DI_SERINFO;
3158     args.serinfo  = info;
3159     args.serpath  = &info->dls_serpath[0];
3160     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
3161
3162     args.flags = LA_SER_LIBPATH;
3163     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
3164         return (-1);
3165
3166     args.flags = LA_SER_RUNPATH;
3167     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
3168         return (-1);
3169
3170     args.flags = LA_SER_CONFIG;
3171     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
3172         return (-1);
3173
3174     args.flags = LA_SER_DEFAULT;
3175     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
3176         return (-1);
3177     return (0);
3178 }
3179
3180 static int
3181 rtld_dirname(const char *path, char *bname)
3182 {
3183     const char *endp;
3184
3185     /* Empty or NULL string gets treated as "." */
3186     if (path == NULL || *path == '\0') {
3187         bname[0] = '.';
3188         bname[1] = '\0';
3189         return (0);
3190     }
3191
3192     /* Strip trailing slashes */
3193     endp = path + strlen(path) - 1;
3194     while (endp > path && *endp == '/')
3195         endp--;
3196
3197     /* Find the start of the dir */
3198     while (endp > path && *endp != '/')
3199         endp--;
3200
3201     /* Either the dir is "/" or there are no slashes */
3202     if (endp == path) {
3203         bname[0] = *endp == '/' ? '/' : '.';
3204         bname[1] = '\0';
3205         return (0);
3206     } else {
3207         do {
3208             endp--;
3209         } while (endp > path && *endp == '/');
3210     }
3211
3212     if (endp - path + 2 > PATH_MAX)
3213     {
3214         _rtld_error("Filename is too long: %s", path);
3215         return(-1);
3216     }
3217
3218     strncpy(bname, path, endp - path + 1);
3219     bname[endp - path + 1] = '\0';
3220     return (0);
3221 }
3222
3223 static int
3224 rtld_dirname_abs(const char *path, char *base)
3225 {
3226         char base_rel[PATH_MAX];
3227
3228         if (rtld_dirname(path, base) == -1)
3229                 return (-1);
3230         if (base[0] == '/')
3231                 return (0);
3232         if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
3233             strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
3234             strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
3235                 return (-1);
3236         strcpy(base, base_rel);
3237         return (0);
3238 }
3239
3240 static void
3241 linkmap_add(Obj_Entry *obj)
3242 {
3243     struct link_map *l = &obj->linkmap;
3244     struct link_map *prev;
3245
3246     obj->linkmap.l_name = obj->path;
3247     obj->linkmap.l_addr = obj->mapbase;
3248     obj->linkmap.l_ld = obj->dynamic;
3249 #ifdef __mips__
3250     /* GDB needs load offset on MIPS to use the symbols */
3251     obj->linkmap.l_offs = obj->relocbase;
3252 #endif
3253
3254     if (r_debug.r_map == NULL) {
3255         r_debug.r_map = l;
3256         return;
3257     }
3258
3259     /*
3260      * Scan to the end of the list, but not past the entry for the
3261      * dynamic linker, which we want to keep at the very end.
3262      */
3263     for (prev = r_debug.r_map;
3264       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
3265       prev = prev->l_next)
3266         ;
3267
3268     /* Link in the new entry. */
3269     l->l_prev = prev;
3270     l->l_next = prev->l_next;
3271     if (l->l_next != NULL)
3272         l->l_next->l_prev = l;
3273     prev->l_next = l;
3274 }
3275
3276 static void
3277 linkmap_delete(Obj_Entry *obj)
3278 {
3279     struct link_map *l = &obj->linkmap;
3280
3281     if (l->l_prev == NULL) {
3282         if ((r_debug.r_map = l->l_next) != NULL)
3283             l->l_next->l_prev = NULL;
3284         return;
3285     }
3286
3287     if ((l->l_prev->l_next = l->l_next) != NULL)
3288         l->l_next->l_prev = l->l_prev;
3289 }
3290
3291 /*
3292  * Function for the debugger to set a breakpoint on to gain control.
3293  *
3294  * The two parameters allow the debugger to easily find and determine
3295  * what the runtime loader is doing and to whom it is doing it.
3296  *
3297  * When the loadhook trap is hit (r_debug_state, set at program
3298  * initialization), the arguments can be found on the stack:
3299  *
3300  *  +8   struct link_map *m
3301  *  +4   struct r_debug  *rd
3302  *  +0   RetAddr
3303  */
3304 void
3305 r_debug_state(struct r_debug* rd, struct link_map *m)
3306 {
3307     /*
3308      * The following is a hack to force the compiler to emit calls to
3309      * this function, even when optimizing.  If the function is empty,
3310      * the compiler is not obliged to emit any code for calls to it,
3311      * even when marked __noinline.  However, gdb depends on those
3312      * calls being made.
3313      */
3314     __asm __volatile("" : : : "memory");
3315 }
3316
3317 /*
3318  * Get address of the pointer variable in the main program.
3319  * Prefer non-weak symbol over the weak one.
3320  */
3321 static const void **
3322 get_program_var_addr(const char *name, RtldLockState *lockstate)
3323 {
3324     SymLook req;
3325     DoneList donelist;
3326
3327     symlook_init(&req, name);
3328     req.lockstate = lockstate;
3329     donelist_init(&donelist);
3330     if (symlook_global(&req, &donelist) != 0)
3331         return (NULL);
3332     if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
3333         return ((const void **)make_function_pointer(req.sym_out,
3334           req.defobj_out));
3335     else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
3336         return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
3337     else
3338         return ((const void **)(req.defobj_out->relocbase +
3339           req.sym_out->st_value));
3340 }
3341
3342 /*
3343  * Set a pointer variable in the main program to the given value.  This
3344  * is used to set key variables such as "environ" before any of the
3345  * init functions are called.
3346  */
3347 static void
3348 set_program_var(const char *name, const void *value)
3349 {
3350     const void **addr;
3351
3352     if ((addr = get_program_var_addr(name, NULL)) != NULL) {
3353         dbg("\"%s\": *%p <-- %p", name, addr, value);
3354         *addr = value;
3355     }
3356 }
3357
3358 /*
3359  * Search the global objects, including dependencies and main object,
3360  * for the given symbol.
3361  */
3362 static int
3363 symlook_global(SymLook *req, DoneList *donelist)
3364 {
3365     SymLook req1;
3366     const Objlist_Entry *elm;
3367     int res;
3368
3369     symlook_init_from_req(&req1, req);
3370
3371     /* Search all objects loaded at program start up. */
3372     if (req->defobj_out == NULL ||
3373       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3374         res = symlook_list(&req1, &list_main, donelist);
3375         if (res == 0 && (req->defobj_out == NULL ||
3376           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3377             req->sym_out = req1.sym_out;
3378             req->defobj_out = req1.defobj_out;
3379             assert(req->defobj_out != NULL);
3380         }
3381     }
3382
3383     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3384     STAILQ_FOREACH(elm, &list_global, link) {
3385         if (req->defobj_out != NULL &&
3386           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3387             break;
3388         res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3389         if (res == 0 && (req->defobj_out == NULL ||
3390           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3391             req->sym_out = req1.sym_out;
3392             req->defobj_out = req1.defobj_out;
3393             assert(req->defobj_out != NULL);
3394         }
3395     }
3396
3397     return (req->sym_out != NULL ? 0 : ESRCH);
3398 }
3399
3400 /*
3401  * Given a symbol name in a referencing object, find the corresponding
3402  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
3403  * no definition was found.  Returns a pointer to the Obj_Entry of the
3404  * defining object via the reference parameter DEFOBJ_OUT.
3405  */
3406 static int
3407 symlook_default(SymLook *req, const Obj_Entry *refobj)
3408 {
3409     DoneList donelist;
3410     const Objlist_Entry *elm;
3411     SymLook req1;
3412     int res;
3413
3414     donelist_init(&donelist);
3415     symlook_init_from_req(&req1, req);
3416
3417     /* Look first in the referencing object if linked symbolically. */
3418     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3419         res = symlook_obj(&req1, refobj);
3420         if (res == 0) {
3421             req->sym_out = req1.sym_out;
3422             req->defobj_out = req1.defobj_out;
3423             assert(req->defobj_out != NULL);
3424         }
3425     }
3426
3427     symlook_global(req, &donelist);
3428
3429     /* Search all dlopened DAGs containing the referencing object. */
3430     STAILQ_FOREACH(elm, &refobj->dldags, link) {
3431         if (req->sym_out != NULL &&
3432           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3433             break;
3434         res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3435         if (res == 0 && (req->sym_out == NULL ||
3436           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3437             req->sym_out = req1.sym_out;
3438             req->defobj_out = req1.defobj_out;
3439             assert(req->defobj_out != NULL);
3440         }
3441     }
3442
3443     /*
3444      * Search the dynamic linker itself, and possibly resolve the
3445      * symbol from there.  This is how the application links to
3446      * dynamic linker services such as dlopen.
3447      */
3448     if (req->sym_out == NULL ||
3449       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3450         res = symlook_obj(&req1, &obj_rtld);
3451         if (res == 0) {
3452             req->sym_out = req1.sym_out;
3453             req->defobj_out = req1.defobj_out;
3454             assert(req->defobj_out != NULL);
3455         }
3456     }
3457
3458     return (req->sym_out != NULL ? 0 : ESRCH);
3459 }
3460
3461 static int
3462 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3463 {
3464     const Elf_Sym *def;
3465     const Obj_Entry *defobj;
3466     const Objlist_Entry *elm;
3467     SymLook req1;
3468     int res;
3469
3470     def = NULL;
3471     defobj = NULL;
3472     STAILQ_FOREACH(elm, objlist, link) {
3473         if (donelist_check(dlp, elm->obj))
3474             continue;
3475         symlook_init_from_req(&req1, req);
3476         if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3477             if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3478                 def = req1.sym_out;
3479                 defobj = req1.defobj_out;
3480                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3481                     break;
3482             }
3483         }
3484     }
3485     if (def != NULL) {
3486         req->sym_out = def;
3487         req->defobj_out = defobj;
3488         return (0);
3489     }
3490     return (ESRCH);
3491 }
3492
3493 /*
3494  * Search the chain of DAGS cointed to by the given Needed_Entry
3495  * for a symbol of the given name.  Each DAG is scanned completely
3496  * before advancing to the next one.  Returns a pointer to the symbol,
3497  * or NULL if no definition was found.
3498  */
3499 static int
3500 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3501 {
3502     const Elf_Sym *def;
3503     const Needed_Entry *n;
3504     const Obj_Entry *defobj;
3505     SymLook req1;
3506     int res;
3507
3508     def = NULL;
3509     defobj = NULL;
3510     symlook_init_from_req(&req1, req);
3511     for (n = needed; n != NULL; n = n->next) {
3512         if (n->obj == NULL ||
3513             (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3514             continue;
3515         if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3516             def = req1.sym_out;
3517             defobj = req1.defobj_out;
3518             if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3519                 break;
3520         }
3521     }
3522     if (def != NULL) {
3523         req->sym_out = def;
3524         req->defobj_out = defobj;
3525         return (0);
3526     }
3527     return (ESRCH);
3528 }
3529
3530 /*
3531  * Search the symbol table of a single shared object for a symbol of
3532  * the given name and version, if requested.  Returns a pointer to the
3533  * symbol, or NULL if no definition was found.  If the object is
3534  * filter, return filtered symbol from filtee.
3535  *
3536  * The symbol's hash value is passed in for efficiency reasons; that
3537  * eliminates many recomputations of the hash value.
3538  */
3539 int
3540 symlook_obj(SymLook *req, const Obj_Entry *obj)
3541 {
3542     DoneList donelist;
3543     SymLook req1;
3544     int flags, res, mres;
3545
3546     /*
3547      * If there is at least one valid hash at this point, we prefer to
3548      * use the faster GNU version if available.
3549      */
3550     if (obj->valid_hash_gnu)
3551         mres = symlook_obj1_gnu(req, obj);
3552     else if (obj->valid_hash_sysv)
3553         mres = symlook_obj1_sysv(req, obj);
3554     else
3555         return (EINVAL);
3556
3557     if (mres == 0) {
3558         if (obj->needed_filtees != NULL) {
3559             flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3560             load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3561             donelist_init(&donelist);
3562             symlook_init_from_req(&req1, req);
3563             res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3564             if (res == 0) {
3565                 req->sym_out = req1.sym_out;
3566                 req->defobj_out = req1.defobj_out;
3567             }
3568             return (res);
3569         }
3570         if (obj->needed_aux_filtees != NULL) {
3571             flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
3572             load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
3573             donelist_init(&donelist);
3574             symlook_init_from_req(&req1, req);
3575             res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3576             if (res == 0) {
3577                 req->sym_out = req1.sym_out;
3578                 req->defobj_out = req1.defobj_out;
3579                 return (res);
3580             }
3581         }
3582     }
3583     return (mres);
3584 }
3585
3586 /* Symbol match routine common to both hash functions */
3587 static bool
3588 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result,
3589     const unsigned long symnum)
3590 {
3591         Elf_Versym verndx;
3592         const Elf_Sym *symp;
3593         const char *strp;
3594
3595         symp = obj->symtab + symnum;
3596         strp = obj->strtab + symp->st_name;
3597
3598         switch (ELF_ST_TYPE(symp->st_info)) {
3599         case STT_FUNC:
3600         case STT_NOTYPE:
3601         case STT_OBJECT:
3602         case STT_COMMON:
3603         case STT_GNU_IFUNC:
3604                 if (symp->st_value == 0)
3605                         return (false);
3606                 /* fallthrough */
3607         case STT_TLS:
3608                 if (symp->st_shndx != SHN_UNDEF)
3609                         break;
3610 #ifndef __mips__
3611                 else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3612                     (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3613                         break;
3614                 /* fallthrough */
3615 #endif
3616         default:
3617                 return (false);
3618         }
3619         if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3620                 return (false);
3621
3622         if (req->ventry == NULL) {
3623                 if (obj->versyms != NULL) {
3624                         verndx = VER_NDX(obj->versyms[symnum]);
3625                         if (verndx > obj->vernum) {
3626                                 _rtld_error(
3627                                     "%s: symbol %s references wrong version %d",
3628                                     obj->path, obj->strtab + symnum, verndx);
3629                                 return (false);
3630                         }
3631                         /*
3632                          * If we are not called from dlsym (i.e. this
3633                          * is a normal relocation from unversioned
3634                          * binary), accept the symbol immediately if
3635                          * it happens to have first version after this
3636                          * shared object became versioned.  Otherwise,
3637                          * if symbol is versioned and not hidden,
3638                          * remember it. If it is the only symbol with
3639                          * this name exported by the shared object, it
3640                          * will be returned as a match by the calling
3641                          * function. If symbol is global (verndx < 2)
3642                          * accept it unconditionally.
3643                          */
3644                         if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3645                             verndx == VER_NDX_GIVEN) {
3646                                 result->sym_out = symp;
3647                                 return (true);
3648                         }
3649                         else if (verndx >= VER_NDX_GIVEN) {
3650                                 if ((obj->versyms[symnum] & VER_NDX_HIDDEN)
3651                                     == 0) {
3652                                         if (result->vsymp == NULL)
3653                                                 result->vsymp = symp;
3654                                         result->vcount++;
3655                                 }
3656                                 return (false);
3657                         }
3658                 }
3659                 result->sym_out = symp;
3660                 return (true);
3661         }
3662         if (obj->versyms == NULL) {
3663                 if (object_match_name(obj, req->ventry->name)) {
3664                         _rtld_error("%s: object %s should provide version %s "
3665                             "for symbol %s", obj_rtld.path, obj->path,
3666                             req->ventry->name, obj->strtab + symnum);
3667                         return (false);
3668                 }
3669         } else {
3670                 verndx = VER_NDX(obj->versyms[symnum]);
3671                 if (verndx > obj->vernum) {
3672                         _rtld_error("%s: symbol %s references wrong version %d",
3673                             obj->path, obj->strtab + symnum, verndx);
3674                         return (false);
3675                 }
3676                 if (obj->vertab[verndx].hash != req->ventry->hash ||
3677                     strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3678                         /*
3679                          * Version does not match. Look if this is a
3680                          * global symbol and if it is not hidden. If
3681                          * global symbol (verndx < 2) is available,
3682                          * use it. Do not return symbol if we are
3683                          * called by dlvsym, because dlvsym looks for
3684                          * a specific version and default one is not
3685                          * what dlvsym wants.
3686                          */
3687                         if ((req->flags & SYMLOOK_DLSYM) ||
3688                             (verndx >= VER_NDX_GIVEN) ||
3689                             (obj->versyms[symnum] & VER_NDX_HIDDEN))
3690                                 return (false);
3691                 }
3692         }
3693         result->sym_out = symp;
3694         return (true);
3695 }
3696
3697 /*
3698  * Search for symbol using SysV hash function.
3699  * obj->buckets is known not to be NULL at this point; the test for this was
3700  * performed with the obj->valid_hash_sysv assignment.
3701  */
3702 static int
3703 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj)
3704 {
3705         unsigned long symnum;
3706         Sym_Match_Result matchres;
3707
3708         matchres.sym_out = NULL;
3709         matchres.vsymp = NULL;
3710         matchres.vcount = 0;
3711
3712         for (symnum = obj->buckets[req->hash % obj->nbuckets];
3713             symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3714                 if (symnum >= obj->nchains)
3715                         return (ESRCH); /* Bad object */
3716
3717                 if (matched_symbol(req, obj, &matchres, symnum)) {
3718                         req->sym_out = matchres.sym_out;
3719                         req->defobj_out = obj;
3720                         return (0);
3721                 }
3722         }
3723         if (matchres.vcount == 1) {
3724                 req->sym_out = matchres.vsymp;
3725                 req->defobj_out = obj;
3726                 return (0);
3727         }
3728         return (ESRCH);
3729 }
3730
3731 /* Search for symbol using GNU hash function */
3732 static int
3733 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj)
3734 {
3735         Elf_Addr bloom_word;
3736         const Elf32_Word *hashval;
3737         Elf32_Word bucket;
3738         Sym_Match_Result matchres;
3739         unsigned int h1, h2;
3740         unsigned long symnum;
3741
3742         matchres.sym_out = NULL;
3743         matchres.vsymp = NULL;
3744         matchres.vcount = 0;
3745
3746         /* Pick right bitmask word from Bloom filter array */
3747         bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) &
3748             obj->maskwords_bm_gnu];
3749
3750         /* Calculate modulus word size of gnu hash and its derivative */
3751         h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1);
3752         h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1));
3753
3754         /* Filter out the "definitely not in set" queries */
3755         if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0)
3756                 return (ESRCH);
3757
3758         /* Locate hash chain and corresponding value element*/
3759         bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu];
3760         if (bucket == 0)
3761                 return (ESRCH);
3762         hashval = &obj->chain_zero_gnu[bucket];
3763         do {
3764                 if (((*hashval ^ req->hash_gnu) >> 1) == 0) {
3765                         symnum = hashval - obj->chain_zero_gnu;
3766                         if (matched_symbol(req, obj, &matchres, symnum)) {
3767                                 req->sym_out = matchres.sym_out;
3768                                 req->defobj_out = obj;
3769                                 return (0);
3770                         }
3771                 }
3772         } while ((*hashval++ & 1) == 0);
3773         if (matchres.vcount == 1) {
3774                 req->sym_out = matchres.vsymp;
3775                 req->defobj_out = obj;
3776                 return (0);
3777         }
3778         return (ESRCH);
3779 }
3780
3781 static void
3782 trace_loaded_objects(Obj_Entry *obj)
3783 {
3784     char        *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3785     int         c;
3786
3787     if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3788         main_local = "";
3789
3790     if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3791         fmt1 = "\t%o => %p (%x)\n";
3792
3793     if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3794         fmt2 = "\t%o (%x)\n";
3795
3796     list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3797
3798     for (; obj; obj = obj->next) {
3799         Needed_Entry            *needed;
3800         char                    *name, *path;
3801         bool                    is_lib;
3802
3803         if (list_containers && obj->needed != NULL)
3804             rtld_printf("%s:\n", obj->path);
3805         for (needed = obj->needed; needed; needed = needed->next) {
3806             if (needed->obj != NULL) {
3807                 if (needed->obj->traced && !list_containers)
3808                     continue;
3809                 needed->obj->traced = true;
3810                 path = needed->obj->path;
3811             } else
3812                 path = "not found";
3813
3814             name = (char *)obj->strtab + needed->name;
3815             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
3816
3817             fmt = is_lib ? fmt1 : fmt2;
3818             while ((c = *fmt++) != '\0') {
3819                 switch (c) {
3820                 default:
3821                     rtld_putchar(c);
3822                     continue;
3823                 case '\\':
3824                     switch (c = *fmt) {
3825                     case '\0':
3826                         continue;
3827                     case 'n':
3828                         rtld_putchar('\n');
3829                         break;
3830                     case 't':
3831                         rtld_putchar('\t');
3832                         break;
3833                     }
3834                     break;
3835                 case '%':
3836                     switch (c = *fmt) {
3837                     case '\0':
3838                         continue;
3839                     case '%':
3840                     default:
3841                         rtld_putchar(c);
3842                         break;
3843                     case 'A':
3844                         rtld_putstr(main_local);
3845                         break;
3846                     case 'a':
3847                         rtld_putstr(obj_main->path);
3848                         break;
3849                     case 'o':
3850                         rtld_putstr(name);
3851                         break;
3852 #if 0
3853                     case 'm':
3854                         rtld_printf("%d", sodp->sod_major);
3855                         break;
3856                     case 'n':
3857                         rtld_printf("%d", sodp->sod_minor);
3858                         break;
3859 #endif
3860                     case 'p':
3861                         rtld_putstr(path);
3862                         break;
3863                     case 'x':
3864                         rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3865                           0);
3866                         break;
3867                     }
3868                     break;
3869                 }
3870                 ++fmt;
3871             }
3872         }
3873     }
3874 }
3875
3876 /*
3877  * Unload a dlopened object and its dependencies from memory and from
3878  * our data structures.  It is assumed that the DAG rooted in the
3879  * object has already been unreferenced, and that the object has a
3880  * reference count of 0.
3881  */
3882 static void
3883 unload_object(Obj_Entry *root)
3884 {
3885     Obj_Entry *obj;
3886     Obj_Entry **linkp;
3887
3888     assert(root->refcount == 0);
3889
3890     /*
3891      * Pass over the DAG removing unreferenced objects from
3892      * appropriate lists.
3893      */
3894     unlink_object(root);
3895
3896     /* Unmap all objects that are no longer referenced. */
3897     linkp = &obj_list->next;
3898     while ((obj = *linkp) != NULL) {
3899         if (obj->refcount == 0) {
3900             LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3901                 obj->path);
3902             dbg("unloading \"%s\"", obj->path);
3903             unload_filtees(root);
3904             munmap(obj->mapbase, obj->mapsize);
3905             linkmap_delete(obj);
3906             *linkp = obj->next;
3907             obj_count--;
3908             obj_free(obj);
3909         } else
3910             linkp = &obj->next;
3911     }
3912     obj_tail = linkp;
3913 }
3914
3915 static void
3916 unlink_object(Obj_Entry *root)
3917 {
3918     Objlist_Entry *elm;
3919
3920     if (root->refcount == 0) {
3921         /* Remove the object from the RTLD_GLOBAL list. */
3922         objlist_remove(&list_global, root);
3923
3924         /* Remove the object from all objects' DAG lists. */
3925         STAILQ_FOREACH(elm, &root->dagmembers, link) {
3926             objlist_remove(&elm->obj->dldags, root);
3927             if (elm->obj != root)
3928                 unlink_object(elm->obj);
3929         }
3930     }
3931 }
3932
3933 static void
3934 ref_dag(Obj_Entry *root)
3935 {
3936     Objlist_Entry *elm;
3937
3938     assert(root->dag_inited);
3939     STAILQ_FOREACH(elm, &root->dagmembers, link)
3940         elm->obj->refcount++;
3941 }
3942
3943 static void
3944 unref_dag(Obj_Entry *root)
3945 {
3946     Objlist_Entry *elm;
3947
3948     assert(root->dag_inited);
3949     STAILQ_FOREACH(elm, &root->dagmembers, link)
3950         elm->obj->refcount--;
3951 }
3952
3953 /*
3954  * Common code for MD __tls_get_addr().
3955  */
3956 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline;
3957 static void *
3958 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset)
3959 {
3960     Elf_Addr *newdtv, *dtv;
3961     RtldLockState lockstate;
3962     int to_copy;
3963
3964     dtv = *dtvp;
3965     /* Check dtv generation in case new modules have arrived */
3966     if (dtv[0] != tls_dtv_generation) {
3967         wlock_acquire(rtld_bind_lock, &lockstate);
3968         newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
3969         to_copy = dtv[1];
3970         if (to_copy > tls_max_index)
3971             to_copy = tls_max_index;
3972         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3973         newdtv[0] = tls_dtv_generation;
3974         newdtv[1] = tls_max_index;
3975         free(dtv);
3976         lock_release(rtld_bind_lock, &lockstate);
3977         dtv = *dtvp = newdtv;
3978     }
3979
3980     /* Dynamically allocate module TLS if necessary */
3981     if (dtv[index + 1] == 0) {
3982         /* Signal safe, wlock will block out signals. */
3983         wlock_acquire(rtld_bind_lock, &lockstate);
3984         if (!dtv[index + 1])
3985             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3986         lock_release(rtld_bind_lock, &lockstate);
3987     }
3988     return ((void *)(dtv[index + 1] + offset));
3989 }
3990
3991 void *
3992 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset)
3993 {
3994         Elf_Addr *dtv;
3995
3996         dtv = *dtvp;
3997         /* Check dtv generation in case new modules have arrived */
3998         if (__predict_true(dtv[0] == tls_dtv_generation &&
3999             dtv[index + 1] != 0))
4000                 return ((void *)(dtv[index + 1] + offset));
4001         return (tls_get_addr_slow(dtvp, index, offset));
4002 }
4003
4004 #if defined(__arm__) || defined(__ia64__) || defined(__powerpc__)
4005
4006 /*
4007  * Allocate Static TLS using the Variant I method.
4008  */
4009 void *
4010 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
4011 {
4012     Obj_Entry *obj;
4013     char *tcb;
4014     Elf_Addr **tls;
4015     Elf_Addr *dtv;
4016     Elf_Addr addr;
4017     int i;
4018
4019     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
4020         return (oldtcb);
4021
4022     assert(tcbsize >= TLS_TCB_SIZE);
4023     tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
4024     tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
4025
4026     if (oldtcb != NULL) {
4027         memcpy(tls, oldtcb, tls_static_space);
4028         free(oldtcb);
4029
4030         /* Adjust the DTV. */
4031         dtv = tls[0];
4032         for (i = 0; i < dtv[1]; i++) {
4033             if (dtv[i+2] >= (Elf_Addr)oldtcb &&
4034                 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
4035                 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
4036             }
4037         }
4038     } else {
4039         dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4040         tls[0] = dtv;
4041         dtv[0] = tls_dtv_generation;
4042         dtv[1] = tls_max_index;
4043
4044         for (obj = objs; obj; obj = obj->next) {
4045             if (obj->tlsoffset > 0) {
4046                 addr = (Elf_Addr)tls + obj->tlsoffset;
4047                 if (obj->tlsinitsize > 0)
4048                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4049                 if (obj->tlssize > obj->tlsinitsize)
4050                     memset((void*) (addr + obj->tlsinitsize), 0,
4051                            obj->tlssize - obj->tlsinitsize);
4052                 dtv[obj->tlsindex + 1] = addr;
4053             }
4054         }
4055     }
4056
4057     return (tcb);
4058 }
4059
4060 void
4061 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4062 {
4063     Elf_Addr *dtv;
4064     Elf_Addr tlsstart, tlsend;
4065     int dtvsize, i;
4066
4067     assert(tcbsize >= TLS_TCB_SIZE);
4068
4069     tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
4070     tlsend = tlsstart + tls_static_space;
4071
4072     dtv = *(Elf_Addr **)tlsstart;
4073     dtvsize = dtv[1];
4074     for (i = 0; i < dtvsize; i++) {
4075         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
4076             free((void*)dtv[i+2]);
4077         }
4078     }
4079     free(dtv);
4080     free(tcb);
4081 }
4082
4083 #endif
4084
4085 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
4086     defined(__mips__)
4087
4088 /*
4089  * Allocate Static TLS using the Variant II method.
4090  */
4091 void *
4092 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
4093 {
4094     Obj_Entry *obj;
4095     size_t size;
4096     char *tls;
4097     Elf_Addr *dtv, *olddtv;
4098     Elf_Addr segbase, oldsegbase, addr;
4099     int i;
4100
4101     size = round(tls_static_space, tcbalign);
4102
4103     assert(tcbsize >= 2*sizeof(Elf_Addr));
4104     tls = xcalloc(1, size + tcbsize);
4105     dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
4106
4107     segbase = (Elf_Addr)(tls + size);
4108     ((Elf_Addr*)segbase)[0] = segbase;
4109     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
4110
4111     dtv[0] = tls_dtv_generation;
4112     dtv[1] = tls_max_index;
4113
4114     if (oldtls) {
4115         /*
4116          * Copy the static TLS block over whole.
4117          */
4118         oldsegbase = (Elf_Addr) oldtls;
4119         memcpy((void *)(segbase - tls_static_space),
4120                (const void *)(oldsegbase - tls_static_space),
4121                tls_static_space);
4122
4123         /*
4124          * If any dynamic TLS blocks have been created tls_get_addr(),
4125          * move them over.
4126          */
4127         olddtv = ((Elf_Addr**)oldsegbase)[1];
4128         for (i = 0; i < olddtv[1]; i++) {
4129             if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
4130                 dtv[i+2] = olddtv[i+2];
4131                 olddtv[i+2] = 0;
4132             }
4133         }
4134
4135         /*
4136          * We assume that this block was the one we created with
4137          * allocate_initial_tls().
4138          */
4139         free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
4140     } else {
4141         for (obj = objs; obj; obj = obj->next) {
4142             if (obj->tlsoffset) {
4143                 addr = segbase - obj->tlsoffset;
4144                 memset((void*) (addr + obj->tlsinitsize),
4145                        0, obj->tlssize - obj->tlsinitsize);
4146                 if (obj->tlsinit)
4147                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
4148                 dtv[obj->tlsindex + 1] = addr;
4149             }
4150         }
4151     }
4152
4153     return (void*) segbase;
4154 }
4155
4156 void
4157 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
4158 {
4159     size_t size;
4160     Elf_Addr* dtv;
4161     int dtvsize, i;
4162     Elf_Addr tlsstart, tlsend;
4163
4164     /*
4165      * Figure out the size of the initial TLS block so that we can
4166      * find stuff which ___tls_get_addr() allocated dynamically.
4167      */
4168     size = round(tls_static_space, tcbalign);
4169
4170     dtv = ((Elf_Addr**)tls)[1];
4171     dtvsize = dtv[1];
4172     tlsend = (Elf_Addr) tls;
4173     tlsstart = tlsend - size;
4174     for (i = 0; i < dtvsize; i++) {
4175         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
4176             free((void*) dtv[i+2]);
4177         }
4178     }
4179
4180     free((void*) tlsstart);
4181     free((void*) dtv);
4182 }
4183
4184 #endif
4185
4186 /*
4187  * Allocate TLS block for module with given index.
4188  */
4189 void *
4190 allocate_module_tls(int index)
4191 {
4192     Obj_Entry* obj;
4193     char* p;
4194
4195     for (obj = obj_list; obj; obj = obj->next) {
4196         if (obj->tlsindex == index)
4197             break;
4198     }
4199     if (!obj) {
4200         _rtld_error("Can't find module with TLS index %d", index);
4201         die();
4202     }
4203
4204     p = malloc(obj->tlssize);
4205     if (p == NULL) {
4206         _rtld_error("Cannot allocate TLS block for index %d", index);
4207         die();
4208     }
4209     memcpy(p, obj->tlsinit, obj->tlsinitsize);
4210     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
4211
4212     return p;
4213 }
4214
4215 bool
4216 allocate_tls_offset(Obj_Entry *obj)
4217 {
4218     size_t off;
4219
4220     if (obj->tls_done)
4221         return true;
4222
4223     if (obj->tlssize == 0) {
4224         obj->tls_done = true;
4225         return true;
4226     }
4227
4228     if (obj->tlsindex == 1)
4229         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
4230     else
4231         off = calculate_tls_offset(tls_last_offset, tls_last_size,
4232                                    obj->tlssize, obj->tlsalign);
4233
4234     /*
4235      * If we have already fixed the size of the static TLS block, we
4236      * must stay within that size. When allocating the static TLS, we
4237      * leave a small amount of space spare to be used for dynamically
4238      * loading modules which use static TLS.
4239      */
4240     if (tls_static_space) {
4241         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
4242             return false;
4243     }
4244
4245     tls_last_offset = obj->tlsoffset = off;
4246     tls_last_size = obj->tlssize;
4247     obj->tls_done = true;
4248
4249     return true;
4250 }
4251
4252 void
4253 free_tls_offset(Obj_Entry *obj)
4254 {
4255
4256     /*
4257      * If we were the last thing to allocate out of the static TLS
4258      * block, we give our space back to the 'allocator'. This is a
4259      * simplistic workaround to allow libGL.so.1 to be loaded and
4260      * unloaded multiple times.
4261      */
4262     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
4263         == calculate_tls_end(tls_last_offset, tls_last_size)) {
4264         tls_last_offset -= obj->tlssize;
4265         tls_last_size = 0;
4266     }
4267 }
4268
4269 void *
4270 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
4271 {
4272     void *ret;
4273     RtldLockState lockstate;
4274
4275     wlock_acquire(rtld_bind_lock, &lockstate);
4276     ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
4277     lock_release(rtld_bind_lock, &lockstate);
4278     return (ret);
4279 }
4280
4281 void
4282 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
4283 {
4284     RtldLockState lockstate;
4285
4286     wlock_acquire(rtld_bind_lock, &lockstate);
4287     free_tls(tcb, tcbsize, tcbalign);
4288     lock_release(rtld_bind_lock, &lockstate);
4289 }
4290
4291 static void
4292 object_add_name(Obj_Entry *obj, const char *name)
4293 {
4294     Name_Entry *entry;
4295     size_t len;
4296
4297     len = strlen(name);
4298     entry = malloc(sizeof(Name_Entry) + len);
4299
4300     if (entry != NULL) {
4301         strcpy(entry->name, name);
4302         STAILQ_INSERT_TAIL(&obj->names, entry, link);
4303     }
4304 }
4305
4306 static int
4307 object_match_name(const Obj_Entry *obj, const char *name)
4308 {
4309     Name_Entry *entry;
4310
4311     STAILQ_FOREACH(entry, &obj->names, link) {
4312         if (strcmp(name, entry->name) == 0)
4313             return (1);
4314     }
4315     return (0);
4316 }
4317
4318 static Obj_Entry *
4319 locate_dependency(const Obj_Entry *obj, const char *name)
4320 {
4321     const Objlist_Entry *entry;
4322     const Needed_Entry *needed;
4323
4324     STAILQ_FOREACH(entry, &list_main, link) {
4325         if (object_match_name(entry->obj, name))
4326             return entry->obj;
4327     }
4328
4329     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
4330         if (strcmp(obj->strtab + needed->name, name) == 0 ||
4331           (needed->obj != NULL && object_match_name(needed->obj, name))) {
4332             /*
4333              * If there is DT_NEEDED for the name we are looking for,
4334              * we are all set.  Note that object might not be found if
4335              * dependency was not loaded yet, so the function can
4336              * return NULL here.  This is expected and handled
4337              * properly by the caller.
4338              */
4339             return (needed->obj);
4340         }
4341     }
4342     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
4343         obj->path, name);
4344     die();
4345 }
4346
4347 static int
4348 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
4349     const Elf_Vernaux *vna)
4350 {
4351     const Elf_Verdef *vd;
4352     const char *vername;
4353
4354     vername = refobj->strtab + vna->vna_name;
4355     vd = depobj->verdef;
4356     if (vd == NULL) {
4357         _rtld_error("%s: version %s required by %s not defined",
4358             depobj->path, vername, refobj->path);
4359         return (-1);
4360     }
4361     for (;;) {
4362         if (vd->vd_version != VER_DEF_CURRENT) {
4363             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4364                 depobj->path, vd->vd_version);
4365             return (-1);
4366         }
4367         if (vna->vna_hash == vd->vd_hash) {
4368             const Elf_Verdaux *aux = (const Elf_Verdaux *)
4369                 ((char *)vd + vd->vd_aux);
4370             if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
4371                 return (0);
4372         }
4373         if (vd->vd_next == 0)
4374             break;
4375         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4376     }
4377     if (vna->vna_flags & VER_FLG_WEAK)
4378         return (0);
4379     _rtld_error("%s: version %s required by %s not found",
4380         depobj->path, vername, refobj->path);
4381     return (-1);
4382 }
4383
4384 static int
4385 rtld_verify_object_versions(Obj_Entry *obj)
4386 {
4387     const Elf_Verneed *vn;
4388     const Elf_Verdef  *vd;
4389     const Elf_Verdaux *vda;
4390     const Elf_Vernaux *vna;
4391     const Obj_Entry *depobj;
4392     int maxvernum, vernum;
4393
4394     if (obj->ver_checked)
4395         return (0);
4396     obj->ver_checked = true;
4397
4398     maxvernum = 0;
4399     /*
4400      * Walk over defined and required version records and figure out
4401      * max index used by any of them. Do very basic sanity checking
4402      * while there.
4403      */
4404     vn = obj->verneed;
4405     while (vn != NULL) {
4406         if (vn->vn_version != VER_NEED_CURRENT) {
4407             _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
4408                 obj->path, vn->vn_version);
4409             return (-1);
4410         }
4411         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4412         for (;;) {
4413             vernum = VER_NEED_IDX(vna->vna_other);
4414             if (vernum > maxvernum)
4415                 maxvernum = vernum;
4416             if (vna->vna_next == 0)
4417                  break;
4418             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4419         }
4420         if (vn->vn_next == 0)
4421             break;
4422         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4423     }
4424
4425     vd = obj->verdef;
4426     while (vd != NULL) {
4427         if (vd->vd_version != VER_DEF_CURRENT) {
4428             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
4429                 obj->path, vd->vd_version);
4430             return (-1);
4431         }
4432         vernum = VER_DEF_IDX(vd->vd_ndx);
4433         if (vernum > maxvernum)
4434                 maxvernum = vernum;
4435         if (vd->vd_next == 0)
4436             break;
4437         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4438     }
4439
4440     if (maxvernum == 0)
4441         return (0);
4442
4443     /*
4444      * Store version information in array indexable by version index.
4445      * Verify that object version requirements are satisfied along the
4446      * way.
4447      */
4448     obj->vernum = maxvernum + 1;
4449     obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry));
4450
4451     vd = obj->verdef;
4452     while (vd != NULL) {
4453         if ((vd->vd_flags & VER_FLG_BASE) == 0) {
4454             vernum = VER_DEF_IDX(vd->vd_ndx);
4455             assert(vernum <= maxvernum);
4456             vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
4457             obj->vertab[vernum].hash = vd->vd_hash;
4458             obj->vertab[vernum].name = obj->strtab + vda->vda_name;
4459             obj->vertab[vernum].file = NULL;
4460             obj->vertab[vernum].flags = 0;
4461         }
4462         if (vd->vd_next == 0)
4463             break;
4464         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4465     }
4466
4467     vn = obj->verneed;
4468     while (vn != NULL) {
4469         depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4470         if (depobj == NULL)
4471             return (-1);
4472         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4473         for (;;) {
4474             if (check_object_provided_version(obj, depobj, vna))
4475                 return (-1);
4476             vernum = VER_NEED_IDX(vna->vna_other);
4477             assert(vernum <= maxvernum);
4478             obj->vertab[vernum].hash = vna->vna_hash;
4479             obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4480             obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4481             obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4482                 VER_INFO_HIDDEN : 0;
4483             if (vna->vna_next == 0)
4484                  break;
4485             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4486         }
4487         if (vn->vn_next == 0)
4488             break;
4489         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4490     }
4491     return 0;
4492 }
4493
4494 static int
4495 rtld_verify_versions(const Objlist *objlist)
4496 {
4497     Objlist_Entry *entry;
4498     int rc;
4499
4500     rc = 0;
4501     STAILQ_FOREACH(entry, objlist, link) {
4502         /*
4503          * Skip dummy objects or objects that have their version requirements
4504          * already checked.
4505          */
4506         if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4507             continue;
4508         if (rtld_verify_object_versions(entry->obj) == -1) {
4509             rc = -1;
4510             if (ld_tracing == NULL)
4511                 break;
4512         }
4513     }
4514     if (rc == 0 || ld_tracing != NULL)
4515         rc = rtld_verify_object_versions(&obj_rtld);
4516     return rc;
4517 }
4518
4519 const Ver_Entry *
4520 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4521 {
4522     Elf_Versym vernum;
4523
4524     if (obj->vertab) {
4525         vernum = VER_NDX(obj->versyms[symnum]);
4526         if (vernum >= obj->vernum) {
4527             _rtld_error("%s: symbol %s has wrong verneed value %d",
4528                 obj->path, obj->strtab + symnum, vernum);
4529         } else if (obj->vertab[vernum].hash != 0) {
4530             return &obj->vertab[vernum];
4531         }
4532     }
4533     return NULL;
4534 }
4535
4536 int
4537 _rtld_get_stack_prot(void)
4538 {
4539
4540         return (stack_prot);
4541 }
4542
4543 static void
4544 map_stacks_exec(RtldLockState *lockstate)
4545 {
4546         void (*thr_map_stacks_exec)(void);
4547
4548         if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4549                 return;
4550         thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4551             get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4552         if (thr_map_stacks_exec != NULL) {
4553                 stack_prot |= PROT_EXEC;
4554                 thr_map_stacks_exec();
4555         }
4556 }
4557
4558 void
4559 symlook_init(SymLook *dst, const char *name)
4560 {
4561
4562         bzero(dst, sizeof(*dst));
4563         dst->name = name;
4564         dst->hash = elf_hash(name);
4565         dst->hash_gnu = gnu_hash(name);
4566 }
4567
4568 static void
4569 symlook_init_from_req(SymLook *dst, const SymLook *src)
4570 {
4571
4572         dst->name = src->name;
4573         dst->hash = src->hash;
4574         dst->hash_gnu = src->hash_gnu;
4575         dst->ventry = src->ventry;
4576         dst->flags = src->flags;
4577         dst->defobj_out = NULL;
4578         dst->sym_out = NULL;
4579         dst->lockstate = src->lockstate;
4580 }
4581
4582 /*
4583  * Overrides for libc_pic-provided functions.
4584  */
4585
4586 int
4587 __getosreldate(void)
4588 {
4589         size_t len;
4590         int oid[2];
4591         int error, osrel;
4592
4593         if (osreldate != 0)
4594                 return (osreldate);
4595
4596         oid[0] = CTL_KERN;
4597         oid[1] = KERN_OSRELDATE;
4598         osrel = 0;
4599         len = sizeof(osrel);
4600         error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4601         if (error == 0 && osrel > 0 && len == sizeof(osrel))
4602                 osreldate = osrel;
4603         return (osreldate);
4604 }
4605
4606 void
4607 exit(int status)
4608 {
4609
4610         _exit(status);
4611 }
4612
4613 void (*__cleanup)(void);
4614 int __isthreaded = 0;
4615 int _thread_autoinit_dummy_decl = 1;
4616
4617 /*
4618  * No unresolved symbols for rtld.
4619  */
4620 void
4621 __pthread_cxa_finalize(struct dl_phdr_info *a)
4622 {
4623 }
4624
4625 void
4626 __stack_chk_fail(void)
4627 {
4628
4629         _rtld_error("stack overflow detected; terminated");
4630         die();
4631 }
4632 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
4633
4634 void
4635 __chk_fail(void)
4636 {
4637
4638         _rtld_error("buffer overflow detected; terminated");
4639         die();
4640 }
4641
4642 const char *
4643 rtld_strerror(int errnum)
4644 {
4645
4646         if (errnum < 0 || errnum >= sys_nerr)
4647                 return ("Unknown error");
4648         return (sys_errlist[errnum]);
4649 }