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