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