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