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