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