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