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