]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - libexec/rtld-elf/rtld.c
MFC r230784:
[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         case PT_GNU_RELRO:
1119             obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr);
1120             obj->relro_size = round_page(ph->p_memsz);
1121             break;
1122         }
1123     }
1124     if (nsegs < 1) {
1125         _rtld_error("%s: too few PT_LOAD segments", path);
1126         return NULL;
1127     }
1128
1129     obj->entry = entry;
1130     return obj;
1131 }
1132
1133 static Obj_Entry *
1134 dlcheck(void *handle)
1135 {
1136     Obj_Entry *obj;
1137
1138     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1139         if (obj == (Obj_Entry *) handle)
1140             break;
1141
1142     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1143         _rtld_error("Invalid shared object handle %p", handle);
1144         return NULL;
1145     }
1146     return obj;
1147 }
1148
1149 /*
1150  * If the given object is already in the donelist, return true.  Otherwise
1151  * add the object to the list and return false.
1152  */
1153 static bool
1154 donelist_check(DoneList *dlp, const Obj_Entry *obj)
1155 {
1156     unsigned int i;
1157
1158     for (i = 0;  i < dlp->num_used;  i++)
1159         if (dlp->objs[i] == obj)
1160             return true;
1161     /*
1162      * Our donelist allocation should always be sufficient.  But if
1163      * our threads locking isn't working properly, more shared objects
1164      * could have been loaded since we allocated the list.  That should
1165      * never happen, but we'll handle it properly just in case it does.
1166      */
1167     if (dlp->num_used < dlp->num_alloc)
1168         dlp->objs[dlp->num_used++] = obj;
1169     return false;
1170 }
1171
1172 /*
1173  * Hash function for symbol table lookup.  Don't even think about changing
1174  * this.  It is specified by the System V ABI.
1175  */
1176 unsigned long
1177 elf_hash(const char *name)
1178 {
1179     const unsigned char *p = (const unsigned char *) name;
1180     unsigned long h = 0;
1181     unsigned long g;
1182
1183     while (*p != '\0') {
1184         h = (h << 4) + *p++;
1185         if ((g = h & 0xf0000000) != 0)
1186             h ^= g >> 24;
1187         h &= ~g;
1188     }
1189     return h;
1190 }
1191
1192 /*
1193  * Find the library with the given name, and return its full pathname.
1194  * The returned string is dynamically allocated.  Generates an error
1195  * message and returns NULL if the library cannot be found.
1196  *
1197  * If the second argument is non-NULL, then it refers to an already-
1198  * loaded shared object, whose library search path will be searched.
1199  *
1200  * The search order is:
1201  *   LD_LIBRARY_PATH
1202  *   rpath in the referencing file
1203  *   ldconfig hints
1204  *   /lib:/usr/lib
1205  */
1206 static char *
1207 find_library(const char *xname, const Obj_Entry *refobj)
1208 {
1209     char *pathname;
1210     char *name;
1211
1212     if (strchr(xname, '/') != NULL) {   /* Hard coded pathname */
1213         if (xname[0] != '/' && !trust) {
1214             _rtld_error("Absolute pathname required for shared object \"%s\"",
1215               xname);
1216             return NULL;
1217         }
1218         if (refobj != NULL && refobj->z_origin)
1219             return origin_subst(xname, refobj->origin_path);
1220         else
1221             return xstrdup(xname);
1222     }
1223
1224     if (libmap_disable || (refobj == NULL) ||
1225         (name = lm_find(refobj->path, xname)) == NULL)
1226         name = (char *)xname;
1227
1228     dbg(" Searching for \"%s\"", name);
1229
1230     if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1231       (refobj != NULL &&
1232       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1233       (pathname = search_library_path(name, gethints())) != NULL ||
1234       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1235         return pathname;
1236
1237     if(refobj != NULL && refobj->path != NULL) {
1238         _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1239           name, basename(refobj->path));
1240     } else {
1241         _rtld_error("Shared object \"%s\" not found", name);
1242     }
1243     return NULL;
1244 }
1245
1246 /*
1247  * Given a symbol number in a referencing object, find the corresponding
1248  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1249  * no definition was found.  Returns a pointer to the Obj_Entry of the
1250  * defining object via the reference parameter DEFOBJ_OUT.
1251  */
1252 const Elf_Sym *
1253 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1254     const Obj_Entry **defobj_out, int flags, SymCache *cache,
1255     RtldLockState *lockstate)
1256 {
1257     const Elf_Sym *ref;
1258     const Elf_Sym *def;
1259     const Obj_Entry *defobj;
1260     SymLook req;
1261     const char *name;
1262     int res;
1263
1264     /*
1265      * If we have already found this symbol, get the information from
1266      * the cache.
1267      */
1268     if (symnum >= refobj->nchains)
1269         return NULL;    /* Bad object */
1270     if (cache != NULL && cache[symnum].sym != NULL) {
1271         *defobj_out = cache[symnum].obj;
1272         return cache[symnum].sym;
1273     }
1274
1275     ref = refobj->symtab + symnum;
1276     name = refobj->strtab + ref->st_name;
1277     def = NULL;
1278     defobj = NULL;
1279
1280     /*
1281      * We don't have to do a full scale lookup if the symbol is local.
1282      * We know it will bind to the instance in this load module; to
1283      * which we already have a pointer (ie ref). By not doing a lookup,
1284      * we not only improve performance, but it also avoids unresolvable
1285      * symbols when local symbols are not in the hash table. This has
1286      * been seen with the ia64 toolchain.
1287      */
1288     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1289         if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1290             _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1291                 symnum);
1292         }
1293         symlook_init(&req, name);
1294         req.flags = flags;
1295         req.ventry = fetch_ventry(refobj, symnum);
1296         req.lockstate = lockstate;
1297         res = symlook_default(&req, refobj);
1298         if (res == 0) {
1299             def = req.sym_out;
1300             defobj = req.defobj_out;
1301         }
1302     } else {
1303         def = ref;
1304         defobj = refobj;
1305     }
1306
1307     /*
1308      * If we found no definition and the reference is weak, treat the
1309      * symbol as having the value zero.
1310      */
1311     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1312         def = &sym_zero;
1313         defobj = obj_main;
1314     }
1315
1316     if (def != NULL) {
1317         *defobj_out = defobj;
1318         /* Record the information in the cache to avoid subsequent lookups. */
1319         if (cache != NULL) {
1320             cache[symnum].sym = def;
1321             cache[symnum].obj = defobj;
1322         }
1323     } else {
1324         if (refobj != &obj_rtld)
1325             _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1326     }
1327     return def;
1328 }
1329
1330 /*
1331  * Return the search path from the ldconfig hints file, reading it if
1332  * necessary.  Returns NULL if there are problems with the hints file,
1333  * or if the search path there is empty.
1334  */
1335 static const char *
1336 gethints(void)
1337 {
1338     static char *hints;
1339
1340     if (hints == NULL) {
1341         int fd;
1342         struct elfhints_hdr hdr;
1343         char *p;
1344
1345         /* Keep from trying again in case the hints file is bad. */
1346         hints = "";
1347
1348         if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1349             return NULL;
1350         if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1351           hdr.magic != ELFHINTS_MAGIC ||
1352           hdr.version != 1) {
1353             close(fd);
1354             return NULL;
1355         }
1356         p = xmalloc(hdr.dirlistlen + 1);
1357         if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1358           read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1359             free(p);
1360             close(fd);
1361             return NULL;
1362         }
1363         hints = p;
1364         close(fd);
1365     }
1366     return hints[0] != '\0' ? hints : NULL;
1367 }
1368
1369 static void
1370 init_dag(Obj_Entry *root)
1371 {
1372     const Needed_Entry *needed;
1373     const Objlist_Entry *elm;
1374     DoneList donelist;
1375
1376     if (root->dag_inited)
1377         return;
1378     donelist_init(&donelist);
1379
1380     /* Root object belongs to own DAG. */
1381     objlist_push_tail(&root->dldags, root);
1382     objlist_push_tail(&root->dagmembers, root);
1383     donelist_check(&donelist, root);
1384
1385     /*
1386      * Add dependencies of root object to DAG in breadth order
1387      * by exploiting the fact that each new object get added
1388      * to the tail of the dagmembers list.
1389      */
1390     STAILQ_FOREACH(elm, &root->dagmembers, link) {
1391         for (needed = elm->obj->needed; needed != NULL; needed = needed->next) {
1392             if (needed->obj == NULL || donelist_check(&donelist, needed->obj))
1393                 continue;
1394             objlist_push_tail(&needed->obj->dldags, root);
1395             objlist_push_tail(&root->dagmembers, needed->obj);
1396         }
1397     }
1398     root->dag_inited = true;
1399 }
1400
1401 /*
1402  * Initialize the dynamic linker.  The argument is the address at which
1403  * the dynamic linker has been mapped into memory.  The primary task of
1404  * this function is to relocate the dynamic linker.
1405  */
1406 static void
1407 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1408 {
1409     Obj_Entry objtmp;   /* Temporary rtld object */
1410     const Elf_Dyn *dyn_rpath;
1411     const Elf_Dyn *dyn_soname;
1412
1413     /*
1414      * Conjure up an Obj_Entry structure for the dynamic linker.
1415      *
1416      * The "path" member can't be initialized yet because string constants
1417      * cannot yet be accessed. Below we will set it correctly.
1418      */
1419     memset(&objtmp, 0, sizeof(objtmp));
1420     objtmp.path = NULL;
1421     objtmp.rtld = true;
1422     objtmp.mapbase = mapbase;
1423 #ifdef PIC
1424     objtmp.relocbase = mapbase;
1425 #endif
1426     if (RTLD_IS_DYNAMIC()) {
1427         objtmp.dynamic = rtld_dynamic(&objtmp);
1428         digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1429         assert(objtmp.needed == NULL);
1430 #if !defined(__mips__)
1431         /* MIPS has a bogus DT_TEXTREL. */
1432         assert(!objtmp.textrel);
1433 #endif
1434
1435         /*
1436          * Temporarily put the dynamic linker entry into the object list, so
1437          * that symbols can be found.
1438          */
1439
1440         relocate_objects(&objtmp, true, &objtmp, NULL);
1441     }
1442
1443     /* Initialize the object list. */
1444     obj_tail = &obj_list;
1445
1446     /* Now that non-local variables can be accesses, copy out obj_rtld. */
1447     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1448
1449     if (aux_info[AT_PAGESZ] != NULL)
1450             pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1451     if (aux_info[AT_OSRELDATE] != NULL)
1452             osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1453
1454     digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1455
1456     /* Replace the path with a dynamically allocated copy. */
1457     obj_rtld.path = xstrdup(PATH_RTLD);
1458
1459     r_debug.r_brk = r_debug_state;
1460     r_debug.r_state = RT_CONSISTENT;
1461 }
1462
1463 /*
1464  * Add the init functions from a needed object list (and its recursive
1465  * needed objects) to "list".  This is not used directly; it is a helper
1466  * function for initlist_add_objects().  The write lock must be held
1467  * when this function is called.
1468  */
1469 static void
1470 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1471 {
1472     /* Recursively process the successor needed objects. */
1473     if (needed->next != NULL)
1474         initlist_add_neededs(needed->next, list);
1475
1476     /* Process the current needed object. */
1477     if (needed->obj != NULL)
1478         initlist_add_objects(needed->obj, &needed->obj->next, list);
1479 }
1480
1481 /*
1482  * Scan all of the DAGs rooted in the range of objects from "obj" to
1483  * "tail" and add their init functions to "list".  This recurses over
1484  * the DAGs and ensure the proper init ordering such that each object's
1485  * needed libraries are initialized before the object itself.  At the
1486  * same time, this function adds the objects to the global finalization
1487  * list "list_fini" in the opposite order.  The write lock must be
1488  * held when this function is called.
1489  */
1490 static void
1491 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1492 {
1493     if (obj->init_scanned || obj->init_done)
1494         return;
1495     obj->init_scanned = true;
1496
1497     /* Recursively process the successor objects. */
1498     if (&obj->next != tail)
1499         initlist_add_objects(obj->next, tail, list);
1500
1501     /* Recursively process the needed objects. */
1502     if (obj->needed != NULL)
1503         initlist_add_neededs(obj->needed, list);
1504
1505     /* Add the object to the init list. */
1506     if (obj->init != (Elf_Addr)NULL)
1507         objlist_push_tail(list, obj);
1508
1509     /* Add the object to the global fini list in the reverse order. */
1510     if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1511         objlist_push_head(&list_fini, obj);
1512         obj->on_fini_list = true;
1513     }
1514 }
1515
1516 #ifndef FPTR_TARGET
1517 #define FPTR_TARGET(f)  ((Elf_Addr) (f))
1518 #endif
1519
1520 static void
1521 free_needed_filtees(Needed_Entry *n)
1522 {
1523     Needed_Entry *needed, *needed1;
1524
1525     for (needed = n; needed != NULL; needed = needed->next) {
1526         if (needed->obj != NULL) {
1527             dlclose(needed->obj);
1528             needed->obj = NULL;
1529         }
1530     }
1531     for (needed = n; needed != NULL; needed = needed1) {
1532         needed1 = needed->next;
1533         free(needed);
1534     }
1535 }
1536
1537 static void
1538 unload_filtees(Obj_Entry *obj)
1539 {
1540
1541     free_needed_filtees(obj->needed_filtees);
1542     obj->needed_filtees = NULL;
1543     free_needed_filtees(obj->needed_aux_filtees);
1544     obj->needed_aux_filtees = NULL;
1545     obj->filtees_loaded = false;
1546 }
1547
1548 static void
1549 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
1550 {
1551
1552     for (; needed != NULL; needed = needed->next) {
1553         needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj,
1554           flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
1555           RTLD_LOCAL);
1556     }
1557 }
1558
1559 static void
1560 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate)
1561 {
1562
1563     lock_restart_for_upgrade(lockstate);
1564     if (!obj->filtees_loaded) {
1565         load_filtee1(obj, obj->needed_filtees, flags);
1566         load_filtee1(obj, obj->needed_aux_filtees, flags);
1567         obj->filtees_loaded = true;
1568     }
1569 }
1570
1571 static int
1572 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags)
1573 {
1574     Obj_Entry *obj1;
1575
1576     for (; needed != NULL; needed = needed->next) {
1577         obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj,
1578           flags & ~RTLD_LO_NOLOAD);
1579         if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0)
1580             return (-1);
1581         if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1582             dbg("obj %s nodelete", obj1->path);
1583             init_dag(obj1);
1584             ref_dag(obj1);
1585             obj1->ref_nodel = true;
1586         }
1587     }
1588     return (0);
1589 }
1590
1591 /*
1592  * Given a shared object, traverse its list of needed objects, and load
1593  * each of them.  Returns 0 on success.  Generates an error message and
1594  * returns -1 on failure.
1595  */
1596 static int
1597 load_needed_objects(Obj_Entry *first, int flags)
1598 {
1599     Obj_Entry *obj;
1600
1601     for (obj = first;  obj != NULL;  obj = obj->next) {
1602         if (process_needed(obj, obj->needed, flags) == -1)
1603             return (-1);
1604     }
1605     return (0);
1606 }
1607
1608 static int
1609 load_preload_objects(void)
1610 {
1611     char *p = ld_preload;
1612     static const char delim[] = " \t:;";
1613
1614     if (p == NULL)
1615         return 0;
1616
1617     p += strspn(p, delim);
1618     while (*p != '\0') {
1619         size_t len = strcspn(p, delim);
1620         char savech;
1621
1622         savech = p[len];
1623         p[len] = '\0';
1624         if (load_object(p, -1, NULL, 0) == NULL)
1625             return -1;  /* XXX - cleanup */
1626         p[len] = savech;
1627         p += len;
1628         p += strspn(p, delim);
1629     }
1630     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1631     return 0;
1632 }
1633
1634 static const char *
1635 printable_path(const char *path)
1636 {
1637
1638         return (path == NULL ? "<unknown>" : path);
1639 }
1640
1641 /*
1642  * Load a shared object into memory, if it is not already loaded.  The
1643  * object may be specified by name or by user-supplied file descriptor
1644  * fd_u. In the later case, the fd_u descriptor is not closed, but its
1645  * duplicate is.
1646  *
1647  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1648  * on failure.
1649  */
1650 static Obj_Entry *
1651 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags)
1652 {
1653     Obj_Entry *obj;
1654     int fd;
1655     struct stat sb;
1656     char *path;
1657
1658     if (name != NULL) {
1659         for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1660             if (object_match_name(obj, name))
1661                 return (obj);
1662         }
1663
1664         path = find_library(name, refobj);
1665         if (path == NULL)
1666             return (NULL);
1667     } else
1668         path = NULL;
1669
1670     /*
1671      * If we didn't find a match by pathname, or the name is not
1672      * supplied, open the file and check again by device and inode.
1673      * This avoids false mismatches caused by multiple links or ".."
1674      * in pathnames.
1675      *
1676      * To avoid a race, we open the file and use fstat() rather than
1677      * using stat().
1678      */
1679     fd = -1;
1680     if (fd_u == -1) {
1681         if ((fd = open(path, O_RDONLY)) == -1) {
1682             _rtld_error("Cannot open \"%s\"", path);
1683             free(path);
1684             return (NULL);
1685         }
1686     } else {
1687         fd = dup(fd_u);
1688         if (fd == -1) {
1689             _rtld_error("Cannot dup fd");
1690             free(path);
1691             return (NULL);
1692         }
1693     }
1694     if (fstat(fd, &sb) == -1) {
1695         _rtld_error("Cannot fstat \"%s\"", printable_path(path));
1696         close(fd);
1697         free(path);
1698         return NULL;
1699     }
1700     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1701         if (obj->ino == sb.st_ino && obj->dev == sb.st_dev)
1702             break;
1703     if (obj != NULL && name != NULL) {
1704         object_add_name(obj, name);
1705         free(path);
1706         close(fd);
1707         return obj;
1708     }
1709     if (flags & RTLD_LO_NOLOAD) {
1710         free(path);
1711         close(fd);
1712         return (NULL);
1713     }
1714
1715     /* First use of this object, so we must map it in */
1716     obj = do_load_object(fd, name, path, &sb, flags);
1717     if (obj == NULL)
1718         free(path);
1719     close(fd);
1720
1721     return obj;
1722 }
1723
1724 static Obj_Entry *
1725 do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1726   int flags)
1727 {
1728     Obj_Entry *obj;
1729     struct statfs fs;
1730
1731     /*
1732      * but first, make sure that environment variables haven't been
1733      * used to circumvent the noexec flag on a filesystem.
1734      */
1735     if (dangerous_ld_env) {
1736         if (fstatfs(fd, &fs) != 0) {
1737             _rtld_error("Cannot fstatfs \"%s\"", printable_path(path));
1738             return NULL;
1739         }
1740         if (fs.f_flags & MNT_NOEXEC) {
1741             _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1742             return NULL;
1743         }
1744     }
1745     dbg("loading \"%s\"", printable_path(path));
1746     obj = map_object(fd, printable_path(path), sbp);
1747     if (obj == NULL)
1748         return NULL;
1749
1750     /*
1751      * If DT_SONAME is present in the object, digest_dynamic2 already
1752      * added it to the object names.
1753      */
1754     if (name != NULL)
1755         object_add_name(obj, name);
1756     obj->path = path;
1757     digest_dynamic(obj, 0);
1758     if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1759       RTLD_LO_DLOPEN) {
1760         dbg("refusing to load non-loadable \"%s\"", obj->path);
1761         _rtld_error("Cannot dlopen non-loadable %s", obj->path);
1762         munmap(obj->mapbase, obj->mapsize);
1763         obj_free(obj);
1764         return (NULL);
1765     }
1766
1767     *obj_tail = obj;
1768     obj_tail = &obj->next;
1769     obj_count++;
1770     obj_loads++;
1771     linkmap_add(obj);   /* for GDB & dlinfo() */
1772     max_stack_flags |= obj->stack_flags;
1773
1774     dbg("  %p .. %p: %s", obj->mapbase,
1775          obj->mapbase + obj->mapsize - 1, obj->path);
1776     if (obj->textrel)
1777         dbg("  WARNING: %s has impure text", obj->path);
1778     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1779         obj->path);    
1780
1781     return obj;
1782 }
1783
1784 static Obj_Entry *
1785 obj_from_addr(const void *addr)
1786 {
1787     Obj_Entry *obj;
1788
1789     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1790         if (addr < (void *) obj->mapbase)
1791             continue;
1792         if (addr < (void *) (obj->mapbase + obj->mapsize))
1793             return obj;
1794     }
1795     return NULL;
1796 }
1797
1798 /*
1799  * Call the finalization functions for each of the objects in "list"
1800  * belonging to the DAG of "root" and referenced once. If NULL "root"
1801  * is specified, every finalization function will be called regardless
1802  * of the reference count and the list elements won't be freed. All of
1803  * the objects are expected to have non-NULL fini functions.
1804  */
1805 static void
1806 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate)
1807 {
1808     Objlist_Entry *elm;
1809     char *saved_msg;
1810
1811     assert(root == NULL || root->refcount == 1);
1812
1813     /*
1814      * Preserve the current error message since a fini function might
1815      * call into the dynamic linker and overwrite it.
1816      */
1817     saved_msg = errmsg_save();
1818     do {
1819         STAILQ_FOREACH(elm, list, link) {
1820             if (root != NULL && (elm->obj->refcount != 1 ||
1821               objlist_find(&root->dagmembers, elm->obj) == NULL))
1822                 continue;
1823             dbg("calling fini function for %s at %p", elm->obj->path,
1824                 (void *)elm->obj->fini);
1825             LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1826                 elm->obj->path);
1827             /* Remove object from fini list to prevent recursive invocation. */
1828             STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1829             /*
1830              * XXX: If a dlopen() call references an object while the
1831              * fini function is in progress, we might end up trying to
1832              * unload the referenced object in dlclose() or the object
1833              * won't be unloaded although its fini function has been
1834              * called.
1835              */
1836             lock_release(rtld_bind_lock, lockstate);
1837             call_initfini_pointer(elm->obj, elm->obj->fini);
1838             wlock_acquire(rtld_bind_lock, lockstate);
1839             /* No need to free anything if process is going down. */
1840             if (root != NULL)
1841                 free(elm);
1842             /*
1843              * We must restart the list traversal after every fini call
1844              * because a dlclose() call from the fini function or from
1845              * another thread might have modified the reference counts.
1846              */
1847             break;
1848         }
1849     } while (elm != NULL);
1850     errmsg_restore(saved_msg);
1851 }
1852
1853 /*
1854  * Call the initialization functions for each of the objects in
1855  * "list".  All of the objects are expected to have non-NULL init
1856  * functions.
1857  */
1858 static void
1859 objlist_call_init(Objlist *list, RtldLockState *lockstate)
1860 {
1861     Objlist_Entry *elm;
1862     Obj_Entry *obj;
1863     char *saved_msg;
1864
1865     /*
1866      * Clean init_scanned flag so that objects can be rechecked and
1867      * possibly initialized earlier if any of vectors called below
1868      * cause the change by using dlopen.
1869      */
1870     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1871         obj->init_scanned = false;
1872
1873     /*
1874      * Preserve the current error message since an init function might
1875      * call into the dynamic linker and overwrite it.
1876      */
1877     saved_msg = errmsg_save();
1878     STAILQ_FOREACH(elm, list, link) {
1879         if (elm->obj->init_done) /* Initialized early. */
1880             continue;
1881         dbg("calling init function for %s at %p", elm->obj->path,
1882             (void *)elm->obj->init);
1883         LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1884             elm->obj->path);
1885         /*
1886          * Race: other thread might try to use this object before current
1887          * one completes the initilization. Not much can be done here
1888          * without better locking.
1889          */
1890         elm->obj->init_done = true;
1891         lock_release(rtld_bind_lock, lockstate);
1892         call_initfini_pointer(elm->obj, elm->obj->init);
1893         wlock_acquire(rtld_bind_lock, lockstate);
1894     }
1895     errmsg_restore(saved_msg);
1896 }
1897
1898 static void
1899 objlist_clear(Objlist *list)
1900 {
1901     Objlist_Entry *elm;
1902
1903     while (!STAILQ_EMPTY(list)) {
1904         elm = STAILQ_FIRST(list);
1905         STAILQ_REMOVE_HEAD(list, link);
1906         free(elm);
1907     }
1908 }
1909
1910 static Objlist_Entry *
1911 objlist_find(Objlist *list, const Obj_Entry *obj)
1912 {
1913     Objlist_Entry *elm;
1914
1915     STAILQ_FOREACH(elm, list, link)
1916         if (elm->obj == obj)
1917             return elm;
1918     return NULL;
1919 }
1920
1921 static void
1922 objlist_init(Objlist *list)
1923 {
1924     STAILQ_INIT(list);
1925 }
1926
1927 static void
1928 objlist_push_head(Objlist *list, Obj_Entry *obj)
1929 {
1930     Objlist_Entry *elm;
1931
1932     elm = NEW(Objlist_Entry);
1933     elm->obj = obj;
1934     STAILQ_INSERT_HEAD(list, elm, link);
1935 }
1936
1937 static void
1938 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1939 {
1940     Objlist_Entry *elm;
1941
1942     elm = NEW(Objlist_Entry);
1943     elm->obj = obj;
1944     STAILQ_INSERT_TAIL(list, elm, link);
1945 }
1946
1947 static void
1948 objlist_remove(Objlist *list, Obj_Entry *obj)
1949 {
1950     Objlist_Entry *elm;
1951
1952     if ((elm = objlist_find(list, obj)) != NULL) {
1953         STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1954         free(elm);
1955     }
1956 }
1957
1958 /*
1959  * Relocate newly-loaded shared objects.  The argument is a pointer to
1960  * the Obj_Entry for the first such object.  All objects from the first
1961  * to the end of the list of objects are relocated.  Returns 0 on success,
1962  * or -1 on failure.
1963  */
1964 static int
1965 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
1966     RtldLockState *lockstate)
1967 {
1968     Obj_Entry *obj;
1969
1970     for (obj = first;  obj != NULL;  obj = obj->next) {
1971         if (obj != rtldobj)
1972             dbg("relocating \"%s\"", obj->path);
1973         if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1974             obj->symtab == NULL || obj->strtab == NULL) {
1975             _rtld_error("%s: Shared object has no run-time symbol table",
1976               obj->path);
1977             return -1;
1978         }
1979
1980         if (obj->textrel) {
1981             /* There are relocations to the write-protected text segment. */
1982             if (mprotect(obj->mapbase, obj->textsize,
1983               PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1984                 _rtld_error("%s: Cannot write-enable text segment: %s",
1985                   obj->path, strerror(errno));
1986                 return -1;
1987             }
1988         }
1989
1990         /* Process the non-PLT relocations. */
1991         if (reloc_non_plt(obj, rtldobj, lockstate))
1992                 return -1;
1993
1994         if (obj->textrel) {     /* Re-protected the text segment. */
1995             if (mprotect(obj->mapbase, obj->textsize,
1996               PROT_READ|PROT_EXEC) == -1) {
1997                 _rtld_error("%s: Cannot write-protect text segment: %s",
1998                   obj->path, strerror(errno));
1999                 return -1;
2000             }
2001         }
2002
2003
2004         /* Set the special PLT or GOT entries. */
2005         init_pltgot(obj);
2006
2007         /* Process the PLT relocations. */
2008         if (reloc_plt(obj) == -1)
2009             return -1;
2010         /* Relocate the jump slots if we are doing immediate binding. */
2011         if (obj->bind_now || bind_now)
2012             if (reloc_jmpslots(obj, lockstate) == -1)
2013                 return -1;
2014
2015         if (obj->relro_size > 0) {
2016             if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
2017                 _rtld_error("%s: Cannot enforce relro protection: %s",
2018                   obj->path, strerror(errno));
2019                 return -1;
2020             }
2021         }
2022
2023         /*
2024          * Set up the magic number and version in the Obj_Entry.  These
2025          * were checked in the crt1.o from the original ElfKit, so we
2026          * set them for backward compatibility.
2027          */
2028         obj->magic = RTLD_MAGIC;
2029         obj->version = RTLD_VERSION;
2030     }
2031
2032     return (0);
2033 }
2034
2035 /*
2036  * The handling of R_MACHINE_IRELATIVE relocations and jumpslots
2037  * referencing STT_GNU_IFUNC symbols is postponed till the other
2038  * relocations are done.  The indirect functions specified as
2039  * ifunc are allowed to call other symbols, so we need to have
2040  * objects relocated before asking for resolution from indirects.
2041  *
2042  * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion,
2043  * instead of the usual lazy handling of PLT slots.  It is
2044  * consistent with how GNU does it.
2045  */
2046 static int
2047 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *lockstate)
2048 {
2049         if (obj->irelative && reloc_iresolve(obj, lockstate) == -1)
2050                 return (-1);
2051         if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
2052             reloc_gnu_ifunc(obj, lockstate) == -1)
2053                 return (-1);
2054         return (0);
2055 }
2056
2057 static int
2058 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lockstate)
2059 {
2060         Obj_Entry *obj;
2061
2062         for (obj = first;  obj != NULL;  obj = obj->next) {
2063                 if (resolve_object_ifunc(obj, bind_now, lockstate) == -1)
2064                         return (-1);
2065         }
2066         return (0);
2067 }
2068
2069 static int
2070 initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockstate)
2071 {
2072         Objlist_Entry *elm;
2073
2074         STAILQ_FOREACH(elm, list, link) {
2075                 if (resolve_object_ifunc(elm->obj, bind_now, lockstate) == -1)
2076                         return (-1);
2077         }
2078         return (0);
2079 }
2080
2081 /*
2082  * Cleanup procedure.  It will be called (by the atexit mechanism) just
2083  * before the process exits.
2084  */
2085 static void
2086 rtld_exit(void)
2087 {
2088     RtldLockState lockstate;
2089
2090     wlock_acquire(rtld_bind_lock, &lockstate);
2091     dbg("rtld_exit()");
2092     objlist_call_fini(&list_fini, NULL, &lockstate);
2093     /* No need to remove the items from the list, since we are exiting. */
2094     if (!libmap_disable)
2095         lm_fini();
2096     lock_release(rtld_bind_lock, &lockstate);
2097 }
2098
2099 static void *
2100 path_enumerate(const char *path, path_enum_proc callback, void *arg)
2101 {
2102 #ifdef COMPAT_32BIT
2103     const char *trans;
2104 #endif
2105     if (path == NULL)
2106         return (NULL);
2107
2108     path += strspn(path, ":;");
2109     while (*path != '\0') {
2110         size_t len;
2111         char  *res;
2112
2113         len = strcspn(path, ":;");
2114 #ifdef COMPAT_32BIT
2115         trans = lm_findn(NULL, path, len);
2116         if (trans)
2117             res = callback(trans, strlen(trans), arg);
2118         else
2119 #endif
2120         res = callback(path, len, arg);
2121
2122         if (res != NULL)
2123             return (res);
2124
2125         path += len;
2126         path += strspn(path, ":;");
2127     }
2128
2129     return (NULL);
2130 }
2131
2132 struct try_library_args {
2133     const char  *name;
2134     size_t       namelen;
2135     char        *buffer;
2136     size_t       buflen;
2137 };
2138
2139 static void *
2140 try_library_path(const char *dir, size_t dirlen, void *param)
2141 {
2142     struct try_library_args *arg;
2143
2144     arg = param;
2145     if (*dir == '/' || trust) {
2146         char *pathname;
2147
2148         if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
2149                 return (NULL);
2150
2151         pathname = arg->buffer;
2152         strncpy(pathname, dir, dirlen);
2153         pathname[dirlen] = '/';
2154         strcpy(pathname + dirlen + 1, arg->name);
2155
2156         dbg("  Trying \"%s\"", pathname);
2157         if (access(pathname, F_OK) == 0) {              /* We found it */
2158             pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
2159             strcpy(pathname, arg->buffer);
2160             return (pathname);
2161         }
2162     }
2163     return (NULL);
2164 }
2165
2166 static char *
2167 search_library_path(const char *name, const char *path)
2168 {
2169     char *p;
2170     struct try_library_args arg;
2171
2172     if (path == NULL)
2173         return NULL;
2174
2175     arg.name = name;
2176     arg.namelen = strlen(name);
2177     arg.buffer = xmalloc(PATH_MAX);
2178     arg.buflen = PATH_MAX;
2179
2180     p = path_enumerate(path, try_library_path, &arg);
2181
2182     free(arg.buffer);
2183
2184     return (p);
2185 }
2186
2187 int
2188 dlclose(void *handle)
2189 {
2190     Obj_Entry *root;
2191     RtldLockState lockstate;
2192
2193     wlock_acquire(rtld_bind_lock, &lockstate);
2194     root = dlcheck(handle);
2195     if (root == NULL) {
2196         lock_release(rtld_bind_lock, &lockstate);
2197         return -1;
2198     }
2199     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
2200         root->path);
2201
2202     /* Unreference the object and its dependencies. */
2203     root->dl_refcount--;
2204
2205     if (root->refcount == 1) {
2206         /*
2207          * The object will be no longer referenced, so we must unload it.
2208          * First, call the fini functions.
2209          */
2210         objlist_call_fini(&list_fini, root, &lockstate);
2211
2212         unref_dag(root);
2213
2214         /* Finish cleaning up the newly-unreferenced objects. */
2215         GDB_STATE(RT_DELETE,&root->linkmap);
2216         unload_object(root);
2217         GDB_STATE(RT_CONSISTENT,NULL);
2218     } else
2219         unref_dag(root);
2220
2221     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
2222     lock_release(rtld_bind_lock, &lockstate);
2223     return 0;
2224 }
2225
2226 char *
2227 dlerror(void)
2228 {
2229     char *msg = error_message;
2230     error_message = NULL;
2231     return msg;
2232 }
2233
2234 /*
2235  * This function is deprecated and has no effect.
2236  */
2237 void
2238 dllockinit(void *context,
2239            void *(*lock_create)(void *context),
2240            void (*rlock_acquire)(void *lock),
2241            void (*wlock_acquire)(void *lock),
2242            void (*lock_release)(void *lock),
2243            void (*lock_destroy)(void *lock),
2244            void (*context_destroy)(void *context))
2245 {
2246     static void *cur_context;
2247     static void (*cur_context_destroy)(void *);
2248
2249     /* Just destroy the context from the previous call, if necessary. */
2250     if (cur_context_destroy != NULL)
2251         cur_context_destroy(cur_context);
2252     cur_context = context;
2253     cur_context_destroy = context_destroy;
2254 }
2255
2256 void *
2257 dlopen(const char *name, int mode)
2258 {
2259
2260         return (rtld_dlopen(name, -1, mode));
2261 }
2262
2263 void *
2264 fdlopen(int fd, int mode)
2265 {
2266
2267         return (rtld_dlopen(NULL, fd, mode));
2268 }
2269
2270 static void *
2271 rtld_dlopen(const char *name, int fd, int mode)
2272 {
2273     RtldLockState lockstate;
2274     int lo_flags;
2275
2276     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
2277     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
2278     if (ld_tracing != NULL) {
2279         rlock_acquire(rtld_bind_lock, &lockstate);
2280         if (sigsetjmp(lockstate.env, 0) != 0)
2281             lock_upgrade(rtld_bind_lock, &lockstate);
2282         environ = (char **)*get_program_var_addr("environ", &lockstate);
2283         lock_release(rtld_bind_lock, &lockstate);
2284     }
2285     lo_flags = RTLD_LO_DLOPEN;
2286     if (mode & RTLD_NODELETE)
2287             lo_flags |= RTLD_LO_NODELETE;
2288     if (mode & RTLD_NOLOAD)
2289             lo_flags |= RTLD_LO_NOLOAD;
2290     if (ld_tracing != NULL)
2291             lo_flags |= RTLD_LO_TRACE;
2292
2293     return (dlopen_object(name, fd, obj_main, lo_flags,
2294       mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
2295 }
2296
2297 static void
2298 dlopen_cleanup(Obj_Entry *obj)
2299 {
2300
2301         obj->dl_refcount--;
2302         unref_dag(obj);
2303         if (obj->refcount == 0)
2304                 unload_object(obj);
2305 }
2306
2307 static Obj_Entry *
2308 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
2309     int mode)
2310 {
2311     Obj_Entry **old_obj_tail;
2312     Obj_Entry *obj;
2313     Objlist initlist;
2314     RtldLockState lockstate;
2315     int result;
2316
2317     objlist_init(&initlist);
2318
2319     wlock_acquire(rtld_bind_lock, &lockstate);
2320     GDB_STATE(RT_ADD,NULL);
2321
2322     old_obj_tail = obj_tail;
2323     obj = NULL;
2324     if (name == NULL && fd == -1) {
2325         obj = obj_main;
2326         obj->refcount++;
2327     } else {
2328         obj = load_object(name, fd, refobj, lo_flags);
2329     }
2330
2331     if (obj) {
2332         obj->dl_refcount++;
2333         if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2334             objlist_push_tail(&list_global, obj);
2335         if (*old_obj_tail != NULL) {            /* We loaded something new. */
2336             assert(*old_obj_tail == obj);
2337             result = load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
2338             init_dag(obj);
2339             ref_dag(obj);
2340             if (result != -1)
2341                 result = rtld_verify_versions(&obj->dagmembers);
2342             if (result != -1 && ld_tracing)
2343                 goto trace;
2344             if (result == -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
2345               == RTLD_NOW, &obj_rtld, &lockstate)) == -1) {
2346                 dlopen_cleanup(obj);
2347                 obj = NULL;
2348             } else {
2349                 /* Make list of init functions to call. */
2350                 initlist_add_objects(obj, &obj->next, &initlist);
2351             }
2352         } else {
2353
2354             /*
2355              * Bump the reference counts for objects on this DAG.  If
2356              * this is the first dlopen() call for the object that was
2357              * already loaded as a dependency, initialize the dag
2358              * starting at it.
2359              */
2360             init_dag(obj);
2361             ref_dag(obj);
2362
2363             if ((lo_flags & RTLD_LO_TRACE) != 0)
2364                 goto trace;
2365         }
2366         if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 ||
2367           obj->z_nodelete) && !obj->ref_nodel) {
2368             dbg("obj %s nodelete", obj->path);
2369             ref_dag(obj);
2370             obj->z_nodelete = obj->ref_nodel = true;
2371         }
2372     }
2373
2374     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2375         name);
2376     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2377
2378     map_stacks_exec(&lockstate);
2379
2380     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW,
2381       &lockstate) == -1) {
2382         objlist_clear(&initlist);
2383         dlopen_cleanup(obj);
2384         lock_release(rtld_bind_lock, &lockstate);
2385         return (NULL);
2386     }
2387
2388     /* Call the init functions. */
2389     objlist_call_init(&initlist, &lockstate);
2390     objlist_clear(&initlist);
2391     lock_release(rtld_bind_lock, &lockstate);
2392     return obj;
2393 trace:
2394     trace_loaded_objects(obj);
2395     lock_release(rtld_bind_lock, &lockstate);
2396     exit(0);
2397 }
2398
2399 static void *
2400 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2401     int flags)
2402 {
2403     DoneList donelist;
2404     const Obj_Entry *obj, *defobj;
2405     const Elf_Sym *def;
2406     SymLook req;
2407     RtldLockState lockstate;
2408     int res;
2409
2410     def = NULL;
2411     defobj = NULL;
2412     symlook_init(&req, name);
2413     req.ventry = ve;
2414     req.flags = flags | SYMLOOK_IN_PLT;
2415     req.lockstate = &lockstate;
2416
2417     rlock_acquire(rtld_bind_lock, &lockstate);
2418     if (sigsetjmp(lockstate.env, 0) != 0)
2419             lock_upgrade(rtld_bind_lock, &lockstate);
2420     if (handle == NULL || handle == RTLD_NEXT ||
2421         handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2422
2423         if ((obj = obj_from_addr(retaddr)) == NULL) {
2424             _rtld_error("Cannot determine caller's shared object");
2425             lock_release(rtld_bind_lock, &lockstate);
2426             return NULL;
2427         }
2428         if (handle == NULL) {   /* Just the caller's shared object. */
2429             res = symlook_obj(&req, obj);
2430             if (res == 0) {
2431                 def = req.sym_out;
2432                 defobj = req.defobj_out;
2433             }
2434         } else if (handle == RTLD_NEXT || /* Objects after caller's */
2435                    handle == RTLD_SELF) { /* ... caller included */
2436             if (handle == RTLD_NEXT)
2437                 obj = obj->next;
2438             for (; obj != NULL; obj = obj->next) {
2439                 res = symlook_obj(&req, obj);
2440                 if (res == 0) {
2441                     if (def == NULL ||
2442                       ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) {
2443                         def = req.sym_out;
2444                         defobj = req.defobj_out;
2445                         if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2446                             break;
2447                     }
2448                 }
2449             }
2450             /*
2451              * Search the dynamic linker itself, and possibly resolve the
2452              * symbol from there.  This is how the application links to
2453              * dynamic linker services such as dlopen.
2454              */
2455             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2456                 res = symlook_obj(&req, &obj_rtld);
2457                 if (res == 0) {
2458                     def = req.sym_out;
2459                     defobj = req.defobj_out;
2460                 }
2461             }
2462         } else {
2463             assert(handle == RTLD_DEFAULT);
2464             res = symlook_default(&req, obj);
2465             if (res == 0) {
2466                 defobj = req.defobj_out;
2467                 def = req.sym_out;
2468             }
2469         }
2470     } else {
2471         if ((obj = dlcheck(handle)) == NULL) {
2472             lock_release(rtld_bind_lock, &lockstate);
2473             return NULL;
2474         }
2475
2476         donelist_init(&donelist);
2477         if (obj->mainprog) {
2478             /* Handle obtained by dlopen(NULL, ...) implies global scope. */
2479             res = symlook_global(&req, &donelist);
2480             if (res == 0) {
2481                 def = req.sym_out;
2482                 defobj = req.defobj_out;
2483             }
2484             /*
2485              * Search the dynamic linker itself, and possibly resolve the
2486              * symbol from there.  This is how the application links to
2487              * dynamic linker services such as dlopen.
2488              */
2489             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2490                 res = symlook_obj(&req, &obj_rtld);
2491                 if (res == 0) {
2492                     def = req.sym_out;
2493                     defobj = req.defobj_out;
2494                 }
2495             }
2496         }
2497         else {
2498             /* Search the whole DAG rooted at the given object. */
2499             res = symlook_list(&req, &obj->dagmembers, &donelist);
2500             if (res == 0) {
2501                 def = req.sym_out;
2502                 defobj = req.defobj_out;
2503             }
2504         }
2505     }
2506
2507     if (def != NULL) {
2508         lock_release(rtld_bind_lock, &lockstate);
2509
2510         /*
2511          * The value required by the caller is derived from the value
2512          * of the symbol. For the ia64 architecture, we need to
2513          * construct a function descriptor which the caller can use to
2514          * call the function with the right 'gp' value. For other
2515          * architectures and for non-functions, the value is simply
2516          * the relocated value of the symbol.
2517          */
2518         if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2519             return (make_function_pointer(def, defobj));
2520         else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
2521             return (rtld_resolve_ifunc(defobj, def));
2522         else
2523             return (defobj->relocbase + def->st_value);
2524     }
2525
2526     _rtld_error("Undefined symbol \"%s\"", name);
2527     lock_release(rtld_bind_lock, &lockstate);
2528     return NULL;
2529 }
2530
2531 void *
2532 dlsym(void *handle, const char *name)
2533 {
2534         return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2535             SYMLOOK_DLSYM);
2536 }
2537
2538 dlfunc_t
2539 dlfunc(void *handle, const char *name)
2540 {
2541         union {
2542                 void *d;
2543                 dlfunc_t f;
2544         } rv;
2545
2546         rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2547             SYMLOOK_DLSYM);
2548         return (rv.f);
2549 }
2550
2551 void *
2552 dlvsym(void *handle, const char *name, const char *version)
2553 {
2554         Ver_Entry ventry;
2555
2556         ventry.name = version;
2557         ventry.file = NULL;
2558         ventry.hash = elf_hash(version);
2559         ventry.flags= 0;
2560         return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2561             SYMLOOK_DLSYM);
2562 }
2563
2564 int
2565 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2566 {
2567     const Obj_Entry *obj;
2568     RtldLockState lockstate;
2569
2570     rlock_acquire(rtld_bind_lock, &lockstate);
2571     obj = obj_from_addr(addr);
2572     if (obj == NULL) {
2573         _rtld_error("No shared object contains address");
2574         lock_release(rtld_bind_lock, &lockstate);
2575         return (0);
2576     }
2577     rtld_fill_dl_phdr_info(obj, phdr_info);
2578     lock_release(rtld_bind_lock, &lockstate);
2579     return (1);
2580 }
2581
2582 int
2583 dladdr(const void *addr, Dl_info *info)
2584 {
2585     const Obj_Entry *obj;
2586     const Elf_Sym *def;
2587     void *symbol_addr;
2588     unsigned long symoffset;
2589     RtldLockState lockstate;
2590
2591     rlock_acquire(rtld_bind_lock, &lockstate);
2592     obj = obj_from_addr(addr);
2593     if (obj == NULL) {
2594         _rtld_error("No shared object contains address");
2595         lock_release(rtld_bind_lock, &lockstate);
2596         return 0;
2597     }
2598     info->dli_fname = obj->path;
2599     info->dli_fbase = obj->mapbase;
2600     info->dli_saddr = (void *)0;
2601     info->dli_sname = NULL;
2602
2603     /*
2604      * Walk the symbol list looking for the symbol whose address is
2605      * closest to the address sent in.
2606      */
2607     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2608         def = obj->symtab + symoffset;
2609
2610         /*
2611          * For skip the symbol if st_shndx is either SHN_UNDEF or
2612          * SHN_COMMON.
2613          */
2614         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2615             continue;
2616
2617         /*
2618          * If the symbol is greater than the specified address, or if it
2619          * is further away from addr than the current nearest symbol,
2620          * then reject it.
2621          */
2622         symbol_addr = obj->relocbase + def->st_value;
2623         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2624             continue;
2625
2626         /* Update our idea of the nearest symbol. */
2627         info->dli_sname = obj->strtab + def->st_name;
2628         info->dli_saddr = symbol_addr;
2629
2630         /* Exact match? */
2631         if (info->dli_saddr == addr)
2632             break;
2633     }
2634     lock_release(rtld_bind_lock, &lockstate);
2635     return 1;
2636 }
2637
2638 int
2639 dlinfo(void *handle, int request, void *p)
2640 {
2641     const Obj_Entry *obj;
2642     RtldLockState lockstate;
2643     int error;
2644
2645     rlock_acquire(rtld_bind_lock, &lockstate);
2646
2647     if (handle == NULL || handle == RTLD_SELF) {
2648         void *retaddr;
2649
2650         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
2651         if ((obj = obj_from_addr(retaddr)) == NULL)
2652             _rtld_error("Cannot determine caller's shared object");
2653     } else
2654         obj = dlcheck(handle);
2655
2656     if (obj == NULL) {
2657         lock_release(rtld_bind_lock, &lockstate);
2658         return (-1);
2659     }
2660
2661     error = 0;
2662     switch (request) {
2663     case RTLD_DI_LINKMAP:
2664         *((struct link_map const **)p) = &obj->linkmap;
2665         break;
2666     case RTLD_DI_ORIGIN:
2667         error = rtld_dirname(obj->path, p);
2668         break;
2669
2670     case RTLD_DI_SERINFOSIZE:
2671     case RTLD_DI_SERINFO:
2672         error = do_search_info(obj, request, (struct dl_serinfo *)p);
2673         break;
2674
2675     default:
2676         _rtld_error("Invalid request %d passed to dlinfo()", request);
2677         error = -1;
2678     }
2679
2680     lock_release(rtld_bind_lock, &lockstate);
2681
2682     return (error);
2683 }
2684
2685 static void
2686 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2687 {
2688
2689         phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2690         phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2691             STAILQ_FIRST(&obj->names)->name : obj->path;
2692         phdr_info->dlpi_phdr = obj->phdr;
2693         phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2694         phdr_info->dlpi_tls_modid = obj->tlsindex;
2695         phdr_info->dlpi_tls_data = obj->tlsinit;
2696         phdr_info->dlpi_adds = obj_loads;
2697         phdr_info->dlpi_subs = obj_loads - obj_count;
2698 }
2699
2700 int
2701 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2702 {
2703     struct dl_phdr_info phdr_info;
2704     const Obj_Entry *obj;
2705     RtldLockState bind_lockstate, phdr_lockstate;
2706     int error;
2707
2708     wlock_acquire(rtld_phdr_lock, &phdr_lockstate);
2709     rlock_acquire(rtld_bind_lock, &bind_lockstate);
2710
2711     error = 0;
2712
2713     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2714         rtld_fill_dl_phdr_info(obj, &phdr_info);
2715         if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2716                 break;
2717
2718     }
2719     lock_release(rtld_bind_lock, &bind_lockstate);
2720     lock_release(rtld_phdr_lock, &phdr_lockstate);
2721
2722     return (error);
2723 }
2724
2725 struct fill_search_info_args {
2726     int          request;
2727     unsigned int flags;
2728     Dl_serinfo  *serinfo;
2729     Dl_serpath  *serpath;
2730     char        *strspace;
2731 };
2732
2733 static void *
2734 fill_search_info(const char *dir, size_t dirlen, void *param)
2735 {
2736     struct fill_search_info_args *arg;
2737
2738     arg = param;
2739
2740     if (arg->request == RTLD_DI_SERINFOSIZE) {
2741         arg->serinfo->dls_cnt ++;
2742         arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2743     } else {
2744         struct dl_serpath *s_entry;
2745
2746         s_entry = arg->serpath;
2747         s_entry->dls_name  = arg->strspace;
2748         s_entry->dls_flags = arg->flags;
2749
2750         strncpy(arg->strspace, dir, dirlen);
2751         arg->strspace[dirlen] = '\0';
2752
2753         arg->strspace += dirlen + 1;
2754         arg->serpath++;
2755     }
2756
2757     return (NULL);
2758 }
2759
2760 static int
2761 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2762 {
2763     struct dl_serinfo _info;
2764     struct fill_search_info_args args;
2765
2766     args.request = RTLD_DI_SERINFOSIZE;
2767     args.serinfo = &_info;
2768
2769     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2770     _info.dls_cnt  = 0;
2771
2772     path_enumerate(ld_library_path, fill_search_info, &args);
2773     path_enumerate(obj->rpath, fill_search_info, &args);
2774     path_enumerate(gethints(), fill_search_info, &args);
2775     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2776
2777
2778     if (request == RTLD_DI_SERINFOSIZE) {
2779         info->dls_size = _info.dls_size;
2780         info->dls_cnt = _info.dls_cnt;
2781         return (0);
2782     }
2783
2784     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2785         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2786         return (-1);
2787     }
2788
2789     args.request  = RTLD_DI_SERINFO;
2790     args.serinfo  = info;
2791     args.serpath  = &info->dls_serpath[0];
2792     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2793
2794     args.flags = LA_SER_LIBPATH;
2795     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2796         return (-1);
2797
2798     args.flags = LA_SER_RUNPATH;
2799     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2800         return (-1);
2801
2802     args.flags = LA_SER_CONFIG;
2803     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2804         return (-1);
2805
2806     args.flags = LA_SER_DEFAULT;
2807     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2808         return (-1);
2809     return (0);
2810 }
2811
2812 static int
2813 rtld_dirname(const char *path, char *bname)
2814 {
2815     const char *endp;
2816
2817     /* Empty or NULL string gets treated as "." */
2818     if (path == NULL || *path == '\0') {
2819         bname[0] = '.';
2820         bname[1] = '\0';
2821         return (0);
2822     }
2823
2824     /* Strip trailing slashes */
2825     endp = path + strlen(path) - 1;
2826     while (endp > path && *endp == '/')
2827         endp--;
2828
2829     /* Find the start of the dir */
2830     while (endp > path && *endp != '/')
2831         endp--;
2832
2833     /* Either the dir is "/" or there are no slashes */
2834     if (endp == path) {
2835         bname[0] = *endp == '/' ? '/' : '.';
2836         bname[1] = '\0';
2837         return (0);
2838     } else {
2839         do {
2840             endp--;
2841         } while (endp > path && *endp == '/');
2842     }
2843
2844     if (endp - path + 2 > PATH_MAX)
2845     {
2846         _rtld_error("Filename is too long: %s", path);
2847         return(-1);
2848     }
2849
2850     strncpy(bname, path, endp - path + 1);
2851     bname[endp - path + 1] = '\0';
2852     return (0);
2853 }
2854
2855 static int
2856 rtld_dirname_abs(const char *path, char *base)
2857 {
2858         char base_rel[PATH_MAX];
2859
2860         if (rtld_dirname(path, base) == -1)
2861                 return (-1);
2862         if (base[0] == '/')
2863                 return (0);
2864         if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2865             strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2866             strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2867                 return (-1);
2868         strcpy(base, base_rel);
2869         return (0);
2870 }
2871
2872 static void
2873 linkmap_add(Obj_Entry *obj)
2874 {
2875     struct link_map *l = &obj->linkmap;
2876     struct link_map *prev;
2877
2878     obj->linkmap.l_name = obj->path;
2879     obj->linkmap.l_addr = obj->mapbase;
2880     obj->linkmap.l_ld = obj->dynamic;
2881 #ifdef __mips__
2882     /* GDB needs load offset on MIPS to use the symbols */
2883     obj->linkmap.l_offs = obj->relocbase;
2884 #endif
2885
2886     if (r_debug.r_map == NULL) {
2887         r_debug.r_map = l;
2888         return;
2889     }
2890
2891     /*
2892      * Scan to the end of the list, but not past the entry for the
2893      * dynamic linker, which we want to keep at the very end.
2894      */
2895     for (prev = r_debug.r_map;
2896       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2897       prev = prev->l_next)
2898         ;
2899
2900     /* Link in the new entry. */
2901     l->l_prev = prev;
2902     l->l_next = prev->l_next;
2903     if (l->l_next != NULL)
2904         l->l_next->l_prev = l;
2905     prev->l_next = l;
2906 }
2907
2908 static void
2909 linkmap_delete(Obj_Entry *obj)
2910 {
2911     struct link_map *l = &obj->linkmap;
2912
2913     if (l->l_prev == NULL) {
2914         if ((r_debug.r_map = l->l_next) != NULL)
2915             l->l_next->l_prev = NULL;
2916         return;
2917     }
2918
2919     if ((l->l_prev->l_next = l->l_next) != NULL)
2920         l->l_next->l_prev = l->l_prev;
2921 }
2922
2923 /*
2924  * Function for the debugger to set a breakpoint on to gain control.
2925  *
2926  * The two parameters allow the debugger to easily find and determine
2927  * what the runtime loader is doing and to whom it is doing it.
2928  *
2929  * When the loadhook trap is hit (r_debug_state, set at program
2930  * initialization), the arguments can be found on the stack:
2931  *
2932  *  +8   struct link_map *m
2933  *  +4   struct r_debug  *rd
2934  *  +0   RetAddr
2935  */
2936 void
2937 r_debug_state(struct r_debug* rd, struct link_map *m)
2938 {
2939     /*
2940      * The following is a hack to force the compiler to emit calls to
2941      * this function, even when optimizing.  If the function is empty,
2942      * the compiler is not obliged to emit any code for calls to it,
2943      * even when marked __noinline.  However, gdb depends on those
2944      * calls being made.
2945      */
2946     __asm __volatile("" : : : "memory");
2947 }
2948
2949 /*
2950  * Get address of the pointer variable in the main program.
2951  * Prefer non-weak symbol over the weak one.
2952  */
2953 static const void **
2954 get_program_var_addr(const char *name, RtldLockState *lockstate)
2955 {
2956     SymLook req;
2957     DoneList donelist;
2958
2959     symlook_init(&req, name);
2960     req.lockstate = lockstate;
2961     donelist_init(&donelist);
2962     if (symlook_global(&req, &donelist) != 0)
2963         return (NULL);
2964     if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC)
2965         return ((const void **)make_function_pointer(req.sym_out,
2966           req.defobj_out));
2967     else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC)
2968         return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out));
2969     else
2970         return ((const void **)(req.defobj_out->relocbase +
2971           req.sym_out->st_value));
2972 }
2973
2974 /*
2975  * Set a pointer variable in the main program to the given value.  This
2976  * is used to set key variables such as "environ" before any of the
2977  * init functions are called.
2978  */
2979 static void
2980 set_program_var(const char *name, const void *value)
2981 {
2982     const void **addr;
2983
2984     if ((addr = get_program_var_addr(name, NULL)) != NULL) {
2985         dbg("\"%s\": *%p <-- %p", name, addr, value);
2986         *addr = value;
2987     }
2988 }
2989
2990 /*
2991  * Search the global objects, including dependencies and main object,
2992  * for the given symbol.
2993  */
2994 static int
2995 symlook_global(SymLook *req, DoneList *donelist)
2996 {
2997     SymLook req1;
2998     const Objlist_Entry *elm;
2999     int res;
3000
3001     symlook_init_from_req(&req1, req);
3002
3003     /* Search all objects loaded at program start up. */
3004     if (req->defobj_out == NULL ||
3005       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3006         res = symlook_list(&req1, &list_main, donelist);
3007         if (res == 0 && (req->defobj_out == NULL ||
3008           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3009             req->sym_out = req1.sym_out;
3010             req->defobj_out = req1.defobj_out;
3011             assert(req->defobj_out != NULL);
3012         }
3013     }
3014
3015     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
3016     STAILQ_FOREACH(elm, &list_global, link) {
3017         if (req->defobj_out != NULL &&
3018           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3019             break;
3020         res = symlook_list(&req1, &elm->obj->dagmembers, donelist);
3021         if (res == 0 && (req->defobj_out == NULL ||
3022           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3023             req->sym_out = req1.sym_out;
3024             req->defobj_out = req1.defobj_out;
3025             assert(req->defobj_out != NULL);
3026         }
3027     }
3028
3029     return (req->sym_out != NULL ? 0 : ESRCH);
3030 }
3031
3032 /*
3033  * Given a symbol name in a referencing object, find the corresponding
3034  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
3035  * no definition was found.  Returns a pointer to the Obj_Entry of the
3036  * defining object via the reference parameter DEFOBJ_OUT.
3037  */
3038 static int
3039 symlook_default(SymLook *req, const Obj_Entry *refobj)
3040 {
3041     DoneList donelist;
3042     const Objlist_Entry *elm;
3043     SymLook req1;
3044     int res;
3045
3046     donelist_init(&donelist);
3047     symlook_init_from_req(&req1, req);
3048
3049     /* Look first in the referencing object if linked symbolically. */
3050     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
3051         res = symlook_obj(&req1, refobj);
3052         if (res == 0) {
3053             req->sym_out = req1.sym_out;
3054             req->defobj_out = req1.defobj_out;
3055             assert(req->defobj_out != NULL);
3056         }
3057     }
3058
3059     symlook_global(req, &donelist);
3060
3061     /* Search all dlopened DAGs containing the referencing object. */
3062     STAILQ_FOREACH(elm, &refobj->dldags, link) {
3063         if (req->sym_out != NULL &&
3064           ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)
3065             break;
3066         res = symlook_list(&req1, &elm->obj->dagmembers, &donelist);
3067         if (res == 0 && (req->sym_out == NULL ||
3068           ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) {
3069             req->sym_out = req1.sym_out;
3070             req->defobj_out = req1.defobj_out;
3071             assert(req->defobj_out != NULL);
3072         }
3073     }
3074
3075     /*
3076      * Search the dynamic linker itself, and possibly resolve the
3077      * symbol from there.  This is how the application links to
3078      * dynamic linker services such as dlopen.
3079      */
3080     if (req->sym_out == NULL ||
3081       ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) {
3082         res = symlook_obj(&req1, &obj_rtld);
3083         if (res == 0) {
3084             req->sym_out = req1.sym_out;
3085             req->defobj_out = req1.defobj_out;
3086             assert(req->defobj_out != NULL);
3087         }
3088     }
3089
3090     return (req->sym_out != NULL ? 0 : ESRCH);
3091 }
3092
3093 static int
3094 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp)
3095 {
3096     const Elf_Sym *def;
3097     const Obj_Entry *defobj;
3098     const Objlist_Entry *elm;
3099     SymLook req1;
3100     int res;
3101
3102     def = NULL;
3103     defobj = NULL;
3104     STAILQ_FOREACH(elm, objlist, link) {
3105         if (donelist_check(dlp, elm->obj))
3106             continue;
3107         symlook_init_from_req(&req1, req);
3108         if ((res = symlook_obj(&req1, elm->obj)) == 0) {
3109             if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3110                 def = req1.sym_out;
3111                 defobj = req1.defobj_out;
3112                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3113                     break;
3114             }
3115         }
3116     }
3117     if (def != NULL) {
3118         req->sym_out = def;
3119         req->defobj_out = defobj;
3120         return (0);
3121     }
3122     return (ESRCH);
3123 }
3124
3125 /*
3126  * Search the chain of DAGS cointed to by the given Needed_Entry
3127  * for a symbol of the given name.  Each DAG is scanned completely
3128  * before advancing to the next one.  Returns a pointer to the symbol,
3129  * or NULL if no definition was found.
3130  */
3131 static int
3132 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp)
3133 {
3134     const Elf_Sym *def;
3135     const Needed_Entry *n;
3136     const Obj_Entry *defobj;
3137     SymLook req1;
3138     int res;
3139
3140     def = NULL;
3141     defobj = NULL;
3142     symlook_init_from_req(&req1, req);
3143     for (n = needed; n != NULL; n = n->next) {
3144         if (n->obj == NULL ||
3145             (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0)
3146             continue;
3147         if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) {
3148             def = req1.sym_out;
3149             defobj = req1.defobj_out;
3150             if (ELF_ST_BIND(def->st_info) != STB_WEAK)
3151                 break;
3152         }
3153     }
3154     if (def != NULL) {
3155         req->sym_out = def;
3156         req->defobj_out = defobj;
3157         return (0);
3158     }
3159     return (ESRCH);
3160 }
3161
3162 /*
3163  * Search the symbol table of a single shared object for a symbol of
3164  * the given name and version, if requested.  Returns a pointer to the
3165  * symbol, or NULL if no definition was found.  If the object is
3166  * filter, return filtered symbol from filtee.
3167  *
3168  * The symbol's hash value is passed in for efficiency reasons; that
3169  * eliminates many recomputations of the hash value.
3170  */
3171 int
3172 symlook_obj(SymLook *req, const Obj_Entry *obj)
3173 {
3174     DoneList donelist;
3175     SymLook req1;
3176     int res, mres;
3177
3178     mres = symlook_obj1(req, obj);
3179     if (mres == 0) {
3180         if (obj->needed_filtees != NULL) {
3181             load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3182             donelist_init(&donelist);
3183             symlook_init_from_req(&req1, req);
3184             res = symlook_needed(&req1, obj->needed_filtees, &donelist);
3185             if (res == 0) {
3186                 req->sym_out = req1.sym_out;
3187                 req->defobj_out = req1.defobj_out;
3188             }
3189             return (res);
3190         }
3191         if (obj->needed_aux_filtees != NULL) {
3192             load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
3193             donelist_init(&donelist);
3194             symlook_init_from_req(&req1, req);
3195             res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
3196             if (res == 0) {
3197                 req->sym_out = req1.sym_out;
3198                 req->defobj_out = req1.defobj_out;
3199                 return (res);
3200             }
3201         }
3202     }
3203     return (mres);
3204 }
3205
3206 static int
3207 symlook_obj1(SymLook *req, const Obj_Entry *obj)
3208 {
3209     unsigned long symnum;
3210     const Elf_Sym *vsymp;
3211     Elf_Versym verndx;
3212     int vcount;
3213
3214     if (obj->buckets == NULL)
3215         return (ESRCH);
3216
3217     vsymp = NULL;
3218     vcount = 0;
3219     symnum = obj->buckets[req->hash % obj->nbuckets];
3220
3221     for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
3222         const Elf_Sym *symp;
3223         const char *strp;
3224
3225         if (symnum >= obj->nchains)
3226             return (ESRCH);     /* Bad object */
3227
3228         symp = obj->symtab + symnum;
3229         strp = obj->strtab + symp->st_name;
3230
3231         switch (ELF_ST_TYPE(symp->st_info)) {
3232         case STT_FUNC:
3233         case STT_NOTYPE:
3234         case STT_OBJECT:
3235         case STT_GNU_IFUNC:
3236             if (symp->st_value == 0)
3237                 continue;
3238                 /* fallthrough */
3239         case STT_TLS:
3240             if (symp->st_shndx != SHN_UNDEF)
3241                 break;
3242 #ifndef __mips__
3243             else if (((req->flags & SYMLOOK_IN_PLT) == 0) &&
3244                  (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
3245                 break;
3246                 /* fallthrough */
3247 #endif
3248         default:
3249             continue;
3250         }
3251         if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0)
3252             continue;
3253
3254         if (req->ventry == NULL) {
3255             if (obj->versyms != NULL) {
3256                 verndx = VER_NDX(obj->versyms[symnum]);
3257                 if (verndx > obj->vernum) {
3258                     _rtld_error("%s: symbol %s references wrong version %d",
3259                         obj->path, obj->strtab + symnum, verndx);
3260                     continue;
3261                 }
3262                 /*
3263                  * If we are not called from dlsym (i.e. this is a normal
3264                  * relocation from unversioned binary), accept the symbol
3265                  * immediately if it happens to have first version after
3266                  * this shared object became versioned. Otherwise, if
3267                  * symbol is versioned and not hidden, remember it. If it
3268                  * is the only symbol with this name exported by the
3269                  * shared object, it will be returned as a match at the
3270                  * end of the function. If symbol is global (verndx < 2)
3271                  * accept it unconditionally.
3272                  */
3273                 if ((req->flags & SYMLOOK_DLSYM) == 0 &&
3274                   verndx == VER_NDX_GIVEN) {
3275                     req->sym_out = symp;
3276                     req->defobj_out = obj;
3277                     return (0);
3278                 }
3279                 else if (verndx >= VER_NDX_GIVEN) {
3280                     if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
3281                         if (vsymp == NULL)
3282                             vsymp = symp;
3283                         vcount ++;
3284                     }
3285                     continue;
3286                 }
3287             }
3288             req->sym_out = symp;
3289             req->defobj_out = obj;
3290             return (0);
3291         } else {
3292             if (obj->versyms == NULL) {
3293                 if (object_match_name(obj, req->ventry->name)) {
3294                     _rtld_error("%s: object %s should provide version %s for "
3295                         "symbol %s", obj_rtld.path, obj->path,
3296                         req->ventry->name, obj->strtab + symnum);
3297                     continue;
3298                 }
3299             } else {
3300                 verndx = VER_NDX(obj->versyms[symnum]);
3301                 if (verndx > obj->vernum) {
3302                     _rtld_error("%s: symbol %s references wrong version %d",
3303                         obj->path, obj->strtab + symnum, verndx);
3304                     continue;
3305                 }
3306                 if (obj->vertab[verndx].hash != req->ventry->hash ||
3307                     strcmp(obj->vertab[verndx].name, req->ventry->name)) {
3308                     /*
3309                      * Version does not match. Look if this is a global symbol
3310                      * and if it is not hidden. If global symbol (verndx < 2)
3311                      * is available, use it. Do not return symbol if we are
3312                      * called by dlvsym, because dlvsym looks for a specific
3313                      * version and default one is not what dlvsym wants.
3314                      */
3315                     if ((req->flags & SYMLOOK_DLSYM) ||
3316                         (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
3317                         (verndx >= VER_NDX_GIVEN))
3318                         continue;
3319                 }
3320             }
3321             req->sym_out = symp;
3322             req->defobj_out = obj;
3323             return (0);
3324         }
3325     }
3326     if (vcount == 1) {
3327         req->sym_out = vsymp;
3328         req->defobj_out = obj;
3329         return (0);
3330     }
3331     return (ESRCH);
3332 }
3333
3334 static void
3335 trace_loaded_objects(Obj_Entry *obj)
3336 {
3337     char        *fmt1, *fmt2, *fmt, *main_local, *list_containers;
3338     int         c;
3339
3340     if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
3341         main_local = "";
3342
3343     if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
3344         fmt1 = "\t%o => %p (%x)\n";
3345
3346     if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
3347         fmt2 = "\t%o (%x)\n";
3348
3349     list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
3350
3351     for (; obj; obj = obj->next) {
3352         Needed_Entry            *needed;
3353         char                    *name, *path;
3354         bool                    is_lib;
3355
3356         if (list_containers && obj->needed != NULL)
3357             rtld_printf("%s:\n", obj->path);
3358         for (needed = obj->needed; needed; needed = needed->next) {
3359             if (needed->obj != NULL) {
3360                 if (needed->obj->traced && !list_containers)
3361                     continue;
3362                 needed->obj->traced = true;
3363                 path = needed->obj->path;
3364             } else
3365                 path = "not found";
3366
3367             name = (char *)obj->strtab + needed->name;
3368             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
3369
3370             fmt = is_lib ? fmt1 : fmt2;
3371             while ((c = *fmt++) != '\0') {
3372                 switch (c) {
3373                 default:
3374                     rtld_putchar(c);
3375                     continue;
3376                 case '\\':
3377                     switch (c = *fmt) {
3378                     case '\0':
3379                         continue;
3380                     case 'n':
3381                         rtld_putchar('\n');
3382                         break;
3383                     case 't':
3384                         rtld_putchar('\t');
3385                         break;
3386                     }
3387                     break;
3388                 case '%':
3389                     switch (c = *fmt) {
3390                     case '\0':
3391                         continue;
3392                     case '%':
3393                     default:
3394                         rtld_putchar(c);
3395                         break;
3396                     case 'A':
3397                         rtld_putstr(main_local);
3398                         break;
3399                     case 'a':
3400                         rtld_putstr(obj_main->path);
3401                         break;
3402                     case 'o':
3403                         rtld_putstr(name);
3404                         break;
3405 #if 0
3406                     case 'm':
3407                         rtld_printf("%d", sodp->sod_major);
3408                         break;
3409                     case 'n':
3410                         rtld_printf("%d", sodp->sod_minor);
3411                         break;
3412 #endif
3413                     case 'p':
3414                         rtld_putstr(path);
3415                         break;
3416                     case 'x':
3417                         rtld_printf("%p", needed->obj ? needed->obj->mapbase :
3418                           0);
3419                         break;
3420                     }
3421                     break;
3422                 }
3423                 ++fmt;
3424             }
3425         }
3426     }
3427 }
3428
3429 /*
3430  * Unload a dlopened object and its dependencies from memory and from
3431  * our data structures.  It is assumed that the DAG rooted in the
3432  * object has already been unreferenced, and that the object has a
3433  * reference count of 0.
3434  */
3435 static void
3436 unload_object(Obj_Entry *root)
3437 {
3438     Obj_Entry *obj;
3439     Obj_Entry **linkp;
3440
3441     assert(root->refcount == 0);
3442
3443     /*
3444      * Pass over the DAG removing unreferenced objects from
3445      * appropriate lists.
3446      */
3447     unlink_object(root);
3448
3449     /* Unmap all objects that are no longer referenced. */
3450     linkp = &obj_list->next;
3451     while ((obj = *linkp) != NULL) {
3452         if (obj->refcount == 0) {
3453             LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3454                 obj->path);
3455             dbg("unloading \"%s\"", obj->path);
3456             unload_filtees(root);
3457             munmap(obj->mapbase, obj->mapsize);
3458             linkmap_delete(obj);
3459             *linkp = obj->next;
3460             obj_count--;
3461             obj_free(obj);
3462         } else
3463             linkp = &obj->next;
3464     }
3465     obj_tail = linkp;
3466 }
3467
3468 static void
3469 unlink_object(Obj_Entry *root)
3470 {
3471     Objlist_Entry *elm;
3472
3473     if (root->refcount == 0) {
3474         /* Remove the object from the RTLD_GLOBAL list. */
3475         objlist_remove(&list_global, root);
3476
3477         /* Remove the object from all objects' DAG lists. */
3478         STAILQ_FOREACH(elm, &root->dagmembers, link) {
3479             objlist_remove(&elm->obj->dldags, root);
3480             if (elm->obj != root)
3481                 unlink_object(elm->obj);
3482         }
3483     }
3484 }
3485
3486 static void
3487 ref_dag(Obj_Entry *root)
3488 {
3489     Objlist_Entry *elm;
3490
3491     assert(root->dag_inited);
3492     STAILQ_FOREACH(elm, &root->dagmembers, link)
3493         elm->obj->refcount++;
3494 }
3495
3496 static void
3497 unref_dag(Obj_Entry *root)
3498 {
3499     Objlist_Entry *elm;
3500
3501     assert(root->dag_inited);
3502     STAILQ_FOREACH(elm, &root->dagmembers, link)
3503         elm->obj->refcount--;
3504 }
3505
3506 /*
3507  * Common code for MD __tls_get_addr().
3508  */
3509 void *
3510 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3511 {
3512     Elf_Addr* dtv = *dtvp;
3513     RtldLockState lockstate;
3514
3515     /* Check dtv generation in case new modules have arrived */
3516     if (dtv[0] != tls_dtv_generation) {
3517         Elf_Addr* newdtv;
3518         int to_copy;
3519
3520         wlock_acquire(rtld_bind_lock, &lockstate);
3521         newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3522         to_copy = dtv[1];
3523         if (to_copy > tls_max_index)
3524             to_copy = tls_max_index;
3525         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3526         newdtv[0] = tls_dtv_generation;
3527         newdtv[1] = tls_max_index;
3528         free(dtv);
3529         lock_release(rtld_bind_lock, &lockstate);
3530         dtv = *dtvp = newdtv;
3531     }
3532
3533     /* Dynamically allocate module TLS if necessary */
3534     if (!dtv[index + 1]) {
3535         /* Signal safe, wlock will block out signals. */
3536             wlock_acquire(rtld_bind_lock, &lockstate);
3537         if (!dtv[index + 1])
3538             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3539         lock_release(rtld_bind_lock, &lockstate);
3540     }
3541     return (void*) (dtv[index + 1] + offset);
3542 }
3543
3544 /* XXX not sure what variants to use for arm. */
3545
3546 #if defined(__ia64__) || defined(__powerpc__)
3547
3548 /*
3549  * Allocate Static TLS using the Variant I method.
3550  */
3551 void *
3552 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3553 {
3554     Obj_Entry *obj;
3555     char *tcb;
3556     Elf_Addr **tls;
3557     Elf_Addr *dtv;
3558     Elf_Addr addr;
3559     int i;
3560
3561     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3562         return (oldtcb);
3563
3564     assert(tcbsize >= TLS_TCB_SIZE);
3565     tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3566     tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3567
3568     if (oldtcb != NULL) {
3569         memcpy(tls, oldtcb, tls_static_space);
3570         free(oldtcb);
3571
3572         /* Adjust the DTV. */
3573         dtv = tls[0];
3574         for (i = 0; i < dtv[1]; i++) {
3575             if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3576                 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3577                 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3578             }
3579         }
3580     } else {
3581         dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3582         tls[0] = dtv;
3583         dtv[0] = tls_dtv_generation;
3584         dtv[1] = tls_max_index;
3585
3586         for (obj = objs; obj; obj = obj->next) {
3587             if (obj->tlsoffset > 0) {
3588                 addr = (Elf_Addr)tls + obj->tlsoffset;
3589                 if (obj->tlsinitsize > 0)
3590                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3591                 if (obj->tlssize > obj->tlsinitsize)
3592                     memset((void*) (addr + obj->tlsinitsize), 0,
3593                            obj->tlssize - obj->tlsinitsize);
3594                 dtv[obj->tlsindex + 1] = addr;
3595             }
3596         }
3597     }
3598
3599     return (tcb);
3600 }
3601
3602 void
3603 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3604 {
3605     Elf_Addr *dtv;
3606     Elf_Addr tlsstart, tlsend;
3607     int dtvsize, i;
3608
3609     assert(tcbsize >= TLS_TCB_SIZE);
3610
3611     tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3612     tlsend = tlsstart + tls_static_space;
3613
3614     dtv = *(Elf_Addr **)tlsstart;
3615     dtvsize = dtv[1];
3616     for (i = 0; i < dtvsize; i++) {
3617         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3618             free((void*)dtv[i+2]);
3619         }
3620     }
3621     free(dtv);
3622     free(tcb);
3623 }
3624
3625 #endif
3626
3627 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3628     defined(__arm__) || defined(__mips__)
3629
3630 /*
3631  * Allocate Static TLS using the Variant II method.
3632  */
3633 void *
3634 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3635 {
3636     Obj_Entry *obj;
3637     size_t size;
3638     char *tls;
3639     Elf_Addr *dtv, *olddtv;
3640     Elf_Addr segbase, oldsegbase, addr;
3641     int i;
3642
3643     size = round(tls_static_space, tcbalign);
3644
3645     assert(tcbsize >= 2*sizeof(Elf_Addr));
3646     tls = calloc(1, size + tcbsize);
3647     dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3648
3649     segbase = (Elf_Addr)(tls + size);
3650     ((Elf_Addr*)segbase)[0] = segbase;
3651     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3652
3653     dtv[0] = tls_dtv_generation;
3654     dtv[1] = tls_max_index;
3655
3656     if (oldtls) {
3657         /*
3658          * Copy the static TLS block over whole.
3659          */
3660         oldsegbase = (Elf_Addr) oldtls;
3661         memcpy((void *)(segbase - tls_static_space),
3662                (const void *)(oldsegbase - tls_static_space),
3663                tls_static_space);
3664
3665         /*
3666          * If any dynamic TLS blocks have been created tls_get_addr(),
3667          * move them over.
3668          */
3669         olddtv = ((Elf_Addr**)oldsegbase)[1];
3670         for (i = 0; i < olddtv[1]; i++) {
3671             if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3672                 dtv[i+2] = olddtv[i+2];
3673                 olddtv[i+2] = 0;
3674             }
3675         }
3676
3677         /*
3678          * We assume that this block was the one we created with
3679          * allocate_initial_tls().
3680          */
3681         free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3682     } else {
3683         for (obj = objs; obj; obj = obj->next) {
3684             if (obj->tlsoffset) {
3685                 addr = segbase - obj->tlsoffset;
3686                 memset((void*) (addr + obj->tlsinitsize),
3687                        0, obj->tlssize - obj->tlsinitsize);
3688                 if (obj->tlsinit)
3689                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3690                 dtv[obj->tlsindex + 1] = addr;
3691             }
3692         }
3693     }
3694
3695     return (void*) segbase;
3696 }
3697
3698 void
3699 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3700 {
3701     size_t size;
3702     Elf_Addr* dtv;
3703     int dtvsize, i;
3704     Elf_Addr tlsstart, tlsend;
3705
3706     /*
3707      * Figure out the size of the initial TLS block so that we can
3708      * find stuff which ___tls_get_addr() allocated dynamically.
3709      */
3710     size = round(tls_static_space, tcbalign);
3711
3712     dtv = ((Elf_Addr**)tls)[1];
3713     dtvsize = dtv[1];
3714     tlsend = (Elf_Addr) tls;
3715     tlsstart = tlsend - size;
3716     for (i = 0; i < dtvsize; i++) {
3717         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3718             free((void*) dtv[i+2]);
3719         }
3720     }
3721
3722     free((void*) tlsstart);
3723     free((void*) dtv);
3724 }
3725
3726 #endif
3727
3728 /*
3729  * Allocate TLS block for module with given index.
3730  */
3731 void *
3732 allocate_module_tls(int index)
3733 {
3734     Obj_Entry* obj;
3735     char* p;
3736
3737     for (obj = obj_list; obj; obj = obj->next) {
3738         if (obj->tlsindex == index)
3739             break;
3740     }
3741     if (!obj) {
3742         _rtld_error("Can't find module with TLS index %d", index);
3743         die();
3744     }
3745
3746     p = malloc(obj->tlssize);
3747     if (p == NULL) {
3748         _rtld_error("Cannot allocate TLS block for index %d", index);
3749         die();
3750     }
3751     memcpy(p, obj->tlsinit, obj->tlsinitsize);
3752     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3753
3754     return p;
3755 }
3756
3757 bool
3758 allocate_tls_offset(Obj_Entry *obj)
3759 {
3760     size_t off;
3761
3762     if (obj->tls_done)
3763         return true;
3764
3765     if (obj->tlssize == 0) {
3766         obj->tls_done = true;
3767         return true;
3768     }
3769
3770     if (obj->tlsindex == 1)
3771         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3772     else
3773         off = calculate_tls_offset(tls_last_offset, tls_last_size,
3774                                    obj->tlssize, obj->tlsalign);
3775
3776     /*
3777      * If we have already fixed the size of the static TLS block, we
3778      * must stay within that size. When allocating the static TLS, we
3779      * leave a small amount of space spare to be used for dynamically
3780      * loading modules which use static TLS.
3781      */
3782     if (tls_static_space) {
3783         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3784             return false;
3785     }
3786
3787     tls_last_offset = obj->tlsoffset = off;
3788     tls_last_size = obj->tlssize;
3789     obj->tls_done = true;
3790
3791     return true;
3792 }
3793
3794 void
3795 free_tls_offset(Obj_Entry *obj)
3796 {
3797
3798     /*
3799      * If we were the last thing to allocate out of the static TLS
3800      * block, we give our space back to the 'allocator'. This is a
3801      * simplistic workaround to allow libGL.so.1 to be loaded and
3802      * unloaded multiple times.
3803      */
3804     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3805         == calculate_tls_end(tls_last_offset, tls_last_size)) {
3806         tls_last_offset -= obj->tlssize;
3807         tls_last_size = 0;
3808     }
3809 }
3810
3811 void *
3812 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3813 {
3814     void *ret;
3815     RtldLockState lockstate;
3816
3817     wlock_acquire(rtld_bind_lock, &lockstate);
3818     ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3819     lock_release(rtld_bind_lock, &lockstate);
3820     return (ret);
3821 }
3822
3823 void
3824 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3825 {
3826     RtldLockState lockstate;
3827
3828     wlock_acquire(rtld_bind_lock, &lockstate);
3829     free_tls(tcb, tcbsize, tcbalign);
3830     lock_release(rtld_bind_lock, &lockstate);
3831 }
3832
3833 static void
3834 object_add_name(Obj_Entry *obj, const char *name)
3835 {
3836     Name_Entry *entry;
3837     size_t len;
3838
3839     len = strlen(name);
3840     entry = malloc(sizeof(Name_Entry) + len);
3841
3842     if (entry != NULL) {
3843         strcpy(entry->name, name);
3844         STAILQ_INSERT_TAIL(&obj->names, entry, link);
3845     }
3846 }
3847
3848 static int
3849 object_match_name(const Obj_Entry *obj, const char *name)
3850 {
3851     Name_Entry *entry;
3852
3853     STAILQ_FOREACH(entry, &obj->names, link) {
3854         if (strcmp(name, entry->name) == 0)
3855             return (1);
3856     }
3857     return (0);
3858 }
3859
3860 static Obj_Entry *
3861 locate_dependency(const Obj_Entry *obj, const char *name)
3862 {
3863     const Objlist_Entry *entry;
3864     const Needed_Entry *needed;
3865
3866     STAILQ_FOREACH(entry, &list_main, link) {
3867         if (object_match_name(entry->obj, name))
3868             return entry->obj;
3869     }
3870
3871     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3872         if (strcmp(obj->strtab + needed->name, name) == 0 ||
3873           (needed->obj != NULL && object_match_name(needed->obj, name))) {
3874             /*
3875              * If there is DT_NEEDED for the name we are looking for,
3876              * we are all set.  Note that object might not be found if
3877              * dependency was not loaded yet, so the function can
3878              * return NULL here.  This is expected and handled
3879              * properly by the caller.
3880              */
3881             return (needed->obj);
3882         }
3883     }
3884     _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3885         obj->path, name);
3886     die();
3887 }
3888
3889 static int
3890 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3891     const Elf_Vernaux *vna)
3892 {
3893     const Elf_Verdef *vd;
3894     const char *vername;
3895
3896     vername = refobj->strtab + vna->vna_name;
3897     vd = depobj->verdef;
3898     if (vd == NULL) {
3899         _rtld_error("%s: version %s required by %s not defined",
3900             depobj->path, vername, refobj->path);
3901         return (-1);
3902     }
3903     for (;;) {
3904         if (vd->vd_version != VER_DEF_CURRENT) {
3905             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3906                 depobj->path, vd->vd_version);
3907             return (-1);
3908         }
3909         if (vna->vna_hash == vd->vd_hash) {
3910             const Elf_Verdaux *aux = (const Elf_Verdaux *)
3911                 ((char *)vd + vd->vd_aux);
3912             if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3913                 return (0);
3914         }
3915         if (vd->vd_next == 0)
3916             break;
3917         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3918     }
3919     if (vna->vna_flags & VER_FLG_WEAK)
3920         return (0);
3921     _rtld_error("%s: version %s required by %s not found",
3922         depobj->path, vername, refobj->path);
3923     return (-1);
3924 }
3925
3926 static int
3927 rtld_verify_object_versions(Obj_Entry *obj)
3928 {
3929     const Elf_Verneed *vn;
3930     const Elf_Verdef  *vd;
3931     const Elf_Verdaux *vda;
3932     const Elf_Vernaux *vna;
3933     const Obj_Entry *depobj;
3934     int maxvernum, vernum;
3935
3936     maxvernum = 0;
3937     /*
3938      * Walk over defined and required version records and figure out
3939      * max index used by any of them. Do very basic sanity checking
3940      * while there.
3941      */
3942     vn = obj->verneed;
3943     while (vn != NULL) {
3944         if (vn->vn_version != VER_NEED_CURRENT) {
3945             _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3946                 obj->path, vn->vn_version);
3947             return (-1);
3948         }
3949         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3950         for (;;) {
3951             vernum = VER_NEED_IDX(vna->vna_other);
3952             if (vernum > maxvernum)
3953                 maxvernum = vernum;
3954             if (vna->vna_next == 0)
3955                  break;
3956             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3957         }
3958         if (vn->vn_next == 0)
3959             break;
3960         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3961     }
3962
3963     vd = obj->verdef;
3964     while (vd != NULL) {
3965         if (vd->vd_version != VER_DEF_CURRENT) {
3966             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3967                 obj->path, vd->vd_version);
3968             return (-1);
3969         }
3970         vernum = VER_DEF_IDX(vd->vd_ndx);
3971         if (vernum > maxvernum)
3972                 maxvernum = vernum;
3973         if (vd->vd_next == 0)
3974             break;
3975         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3976     }
3977
3978     if (maxvernum == 0)
3979         return (0);
3980
3981     /*
3982      * Store version information in array indexable by version index.
3983      * Verify that object version requirements are satisfied along the
3984      * way.
3985      */
3986     obj->vernum = maxvernum + 1;
3987     obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3988
3989     vd = obj->verdef;
3990     while (vd != NULL) {
3991         if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3992             vernum = VER_DEF_IDX(vd->vd_ndx);
3993             assert(vernum <= maxvernum);
3994             vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3995             obj->vertab[vernum].hash = vd->vd_hash;
3996             obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3997             obj->vertab[vernum].file = NULL;
3998             obj->vertab[vernum].flags = 0;
3999         }
4000         if (vd->vd_next == 0)
4001             break;
4002         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
4003     }
4004
4005     vn = obj->verneed;
4006     while (vn != NULL) {
4007         depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
4008         if (depobj == NULL)
4009             return (-1);
4010         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
4011         for (;;) {
4012             if (check_object_provided_version(obj, depobj, vna))
4013                 return (-1);
4014             vernum = VER_NEED_IDX(vna->vna_other);
4015             assert(vernum <= maxvernum);
4016             obj->vertab[vernum].hash = vna->vna_hash;
4017             obj->vertab[vernum].name = obj->strtab + vna->vna_name;
4018             obj->vertab[vernum].file = obj->strtab + vn->vn_file;
4019             obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
4020                 VER_INFO_HIDDEN : 0;
4021             if (vna->vna_next == 0)
4022                  break;
4023             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
4024         }
4025         if (vn->vn_next == 0)
4026             break;
4027         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
4028     }
4029     return 0;
4030 }
4031
4032 static int
4033 rtld_verify_versions(const Objlist *objlist)
4034 {
4035     Objlist_Entry *entry;
4036     int rc;
4037
4038     rc = 0;
4039     STAILQ_FOREACH(entry, objlist, link) {
4040         /*
4041          * Skip dummy objects or objects that have their version requirements
4042          * already checked.
4043          */
4044         if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
4045             continue;
4046         if (rtld_verify_object_versions(entry->obj) == -1) {
4047             rc = -1;
4048             if (ld_tracing == NULL)
4049                 break;
4050         }
4051     }
4052     if (rc == 0 || ld_tracing != NULL)
4053         rc = rtld_verify_object_versions(&obj_rtld);
4054     return rc;
4055 }
4056
4057 const Ver_Entry *
4058 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
4059 {
4060     Elf_Versym vernum;
4061
4062     if (obj->vertab) {
4063         vernum = VER_NDX(obj->versyms[symnum]);
4064         if (vernum >= obj->vernum) {
4065             _rtld_error("%s: symbol %s has wrong verneed value %d",
4066                 obj->path, obj->strtab + symnum, vernum);
4067         } else if (obj->vertab[vernum].hash != 0) {
4068             return &obj->vertab[vernum];
4069         }
4070     }
4071     return NULL;
4072 }
4073
4074 int
4075 _rtld_get_stack_prot(void)
4076 {
4077
4078         return (stack_prot);
4079 }
4080
4081 static void
4082 map_stacks_exec(RtldLockState *lockstate)
4083 {
4084         void (*thr_map_stacks_exec)(void);
4085
4086         if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0)
4087                 return;
4088         thr_map_stacks_exec = (void (*)(void))(uintptr_t)
4089             get_program_var_addr("__pthread_map_stacks_exec", lockstate);
4090         if (thr_map_stacks_exec != NULL) {
4091                 stack_prot |= PROT_EXEC;
4092                 thr_map_stacks_exec();
4093         }
4094 }
4095
4096 void
4097 symlook_init(SymLook *dst, const char *name)
4098 {
4099
4100         bzero(dst, sizeof(*dst));
4101         dst->name = name;
4102         dst->hash = elf_hash(name);
4103 }
4104
4105 static void
4106 symlook_init_from_req(SymLook *dst, const SymLook *src)
4107 {
4108
4109         dst->name = src->name;
4110         dst->hash = src->hash;
4111         dst->ventry = src->ventry;
4112         dst->flags = src->flags;
4113         dst->defobj_out = NULL;
4114         dst->sym_out = NULL;
4115         dst->lockstate = src->lockstate;
4116 }
4117
4118 /*
4119  * Overrides for libc_pic-provided functions.
4120  */
4121
4122 int
4123 __getosreldate(void)
4124 {
4125         size_t len;
4126         int oid[2];
4127         int error, osrel;
4128
4129         if (osreldate != 0)
4130                 return (osreldate);
4131
4132         oid[0] = CTL_KERN;
4133         oid[1] = KERN_OSRELDATE;
4134         osrel = 0;
4135         len = sizeof(osrel);
4136         error = sysctl(oid, 2, &osrel, &len, NULL, 0);
4137         if (error == 0 && osrel > 0 && len == sizeof(osrel))
4138                 osreldate = osrel;
4139         return (osreldate);
4140 }
4141
4142 /*
4143  * No unresolved symbols for rtld.
4144  */
4145 void
4146 __pthread_cxa_finalize(struct dl_phdr_info *a)
4147 {
4148 }