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