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