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