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