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