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