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