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