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