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